插入排序
#include <iostream> #include <ctime> void insert_sort(int a[],int length) { for(int i=1;i<length;i++) { int key=a[i]; int j=i-1; while(j>=0 && key<a[j] ) { a[j+1]=a[j]; j--; } a[j+1]=key; } } void inline GetData(int a[],int length) { for(int i=0;i<length;i++) std::cout<<a[i]<<","; } int main(void) { const int len=20; int a[len]={}; srand((unsigned)time(0)); for(int n=0;n<len;n++) a[n]=rand()%len; std::cout<<"before: "; GetData(a,len); std::cout<<std::endl<<"after: "; insert_sort(a,len); GetData(a,len); return 0; }
递归方法:
void insert_sort(int a[],int length) { if(length>1) { insert_sort(a,length-1); int tmp=a[length-1]; int i=0; for(i=length-2;i>=0;--i) { if(tmp<a[i]) a[i+1]=a[i]; else break; } a[i+1]=tmp; } }