步骤
1.1、首先对数组的前两个数据进行从小到大的排序
2.2、接着将第3个数据与排好的两个数据比较,将第3个数据插入到合适的位置
2.3、然后,将第4个数据插入到已排序好的前3个数据
2.4、不断重复上述的过程。
// InsertSort.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include<IOSTREAM> #include<CSTDIO> #include<CSTDLIB> #include<CSTRING> #include<CTIME> using namespace std; #define SIZE 10 void InsertSort(int *a, int len) { int i, j, t, h; for (i = 1; i < len; i++) { t = a[i]; j = i -1; while(j >= 0 && t < a[j]) { a[j+1] = a[j]; j--; } a[j+1] = t; cout<<"sort "<<i<<" step result"<<endl; for (h = 0; h < len; h++) { cout<<a[h]<<" "; } cout<<endl; } } int main(int argc, char* argv[]) { int array[SIZE], i = 0; srand(time(NULL)); for (;i < SIZE; i++) { array[i] = rand() /1000 + 100; } cout<<"before sort -------------"<<endl; for (i = 0; i < SIZE; i++) { cout<<array[i]<<" "; } cout<<endl; InsertSort(array, SIZE); cout<<"Sort: ------------------"<<endl; for (i = 0; i < SIZE; i++) { cout<<array[i]<<" "; } cout<<endl; getchar(); return 0; }
before sort ------------- 113 119 127 100 113 106 110 117 107 121 sort 1 step result 113 119 127 100 113 106 110 117 107 121 sort 2 step result 113 119 127 100 113 106 110 117 107 121 sort 3 step result 100 113 119 127 113 106 110 117 107 121 sort 4 step result 100 113 113 119 127 106 110 117 107 121 sort 5 step result 100 106 113 113 119 127 110 117 107 121 sort 6 step result 100 106 110 113 113 119 127 117 107 121 sort 7 step result 100 106 110 113 113 117 119 127 107 121 sort 8 step result 100 106 107 110 113 113 117 119 127 121 sort 9 step result 100 106 107 110 113 113 117 119 121 127 Sort: ------------------ 100 106 107 110 113 113 117 119 121 127