- #include<stdio.h>
- //输出数组
- void printdata(int r[],int n) {
- int i;
- for(i=1;i<n;i++)
- printf("%d ",r[i]);
- }
- //直接插入排序
- void InsertSort(int r[],int n) {
- int i,j;
- for(i=2;i<n;i++) {
- if(r[i]<r[i-1]) {
- r[0] = r[i];
- for(j=i-1;r[0]<r[j];j--)
- r[j+1]=r[j];
- r[j+1]=r[0];
- }
- }
- printdata(r,n);
- }
- //折半插入排序
- void BinSort(int r[],int n) {
- int i,j,low,high,m;
- for(i=2;i<n;i++) {
- r[0]=r[i];
- low = 1;
- high = i-1;
- while(low<=high) {
- m = (low+high)/2;
- if(r[0]<r[m])
- high = m-1;
- else
- low = m+1;
- }
- for(j=i-1;j>=high+1;--j)
- r[j+1] = r[j];
- r[high+1] = r[0];
- }
- printdata(r,n);
- }
- void main() {
- int a[9] = {0,1,7,3,2,0,5,6,8};
- int b[9];
- int i, n = 9;
- for(i=0;i<=n-1;i++)
- b[i]=a[i];
- printf("\nInsertSort output:");
- InsertSort(b,n);
- for(i=0;i<=n-1;i++)
- b[i]=a[i];
- printf("\nBinSort output:");
- BinSort(b,n);
- }
转载于:https://blog.51cto.com/asheng0321/729910