#include <iostream>
#include <cstdlib>
using namespace std;
void print(int* pData, int count){
for (int i = 0; i< count; i++) {
cout << pData[i] << " ";
}
cout << endl;
}
void insertSort(int *pData, int count){
for (int i = 1; i < count; i++) {
int key = pData[i];
int j = i-1;
while(j>=0 && key<pData[j]){
pData[j+1] = pData[j];
--j;
}
pData[j+1] = key;
cout << "The "<< i <<" round:" << endl;
print(pData, 6);
cout << "----------------------------" << endl;
}
}
int main() {
int data[] = {5,2,6,1,8,7};
insertSort(data, 6);
cout << "The sort result:" << endl;
print(data, 6);
return 0;
}
运行结果:
The 1 round:
2 5 6 1 8 7
----------------------------
The 2 round:
2 5 6 1 8 7
----------------------------
The 3 round:
1 2 5 6 8 7
----------------------------
The 4 round:
1 2 5 6 8 7
----------------------------
The 5 round:
1 2 5 6 7 8
----------------------------
The sort result:
1 2 5 6 7 8