按照書上的說法,排序是電腦程式設計中的一種重要操作,它的功能是將一個資料元素(或記錄)的任意序列,重新排列成一個按關鍵字有序的序列。
為了方便我們直接對整型數組進行排序。將數組元素按照小到大的順序排列。以後遇到什麼記錄、結構體排序演算法也一樣。這裡只給出實現,演算法說明請看嚴蔚敏的書。
//直接插入排序
void InsertSort(int array[],size_t size)//數組的array空出來,做哨兵。size為數組的長度{ for(int i=2;i<size;++i) { if(array[i]<array[i-1]) { array[0]=array[i]; array[i]=array[i-1]; int j; for(j=i-2;array[0]<array[j];--j) { array[j+1]=array[j]; }//for array[j+1]=array[0]; }//if }//for }
//折半插入排序
void BInsertSort(int array[],size_t size){for (size_t i=1;i<size;i++){int tem=array[i];int low=0,high=i-1;while (low<=high){int m=(low+high)/2;if (tem<array[m]){high=m-1;}else low=m+1;}//whilefor (int j=i-1;j>=high+1;--j){array[j+1]=array[j];}array[high+1]=tem;}//for}
//2-路插入排序
void TWayInsertSort(int array[],size_t size) { int first,final; first=final=0; int tem[size]; tem[0]=array[0]; for(int i=1;i<size;i++) { if(array[i]>=tem[final]) { tem[++final]=array[i]; } else if(array[i]<=tem[first]) { first=(first-1+size)%size; tem[first]=array[i]; } else//進行折半插入排序,在網上看了很多人的這部分是直接插入的。 { int low,high; if(array[i]<tem[0]) { low=first; high=size-1; } else { low=0; high=final; } int m; while(low<=high) { m=(low+high)/2; if(array[i]<tem[m]) high=m-1; else low=m+1; } for(int j=final;j!=high;j=(j-1+size)%size) { tem[(j+1)%size]=tem[j]; } tem[(high+1)%size]=array[i]; final++; }//else}//forfor(int i=0,j=first;i<size;j=(j+1)%size,++i)array[i]=tem[j];}
//2-路插入排序的另一個版本
void BInsertSort(int array[],size_t size){for (size_t i=1;i<size;i++){int tem=array[i];int low=0,high=i-1;while (low<=high){int m=(low+high)/2;if (tem<array[m]){high=m-1;}else low=m+1;}//whilefor (int j=i-1;j>=high+1;--j){array[j+1]=array[j];}array[high+1]=tem;}//for}