按照书上的说法,排序是计算机程序设计中的一种重要操作,它的功能是将一个数据元素(或记录)的任意序列,重新排列成一个按关键字有序的序列。
为了方便我们直接对整型数组进行排序。将数组元素按照小到大的顺序排列。以后遇到什么记录、结构体排序算法也一样。这里只给出实现,算法说明请看严蔚敏的书。
//直接插入排序
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; }//while for (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 }//for for(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; }//while for (int j=i-1;j>=high+1;--j) { array[j+1]=array[j]; } array[high+1]=tem; }//for }