折半插入排序
#include"stdio.h" #include"stdlib.h" typedef struct SqList{ int * elem; int length; int MaxSize; }SqList; void CreatList(SqList &L) { L.elem=(int *)malloc(100 * sizeof(int)); if(!L.elem) exit(0); else { L.length = 0; L.MaxSize = 100; int i, n; printf("please shu ru yuan su ge shu:\n"); scanf("%d", &n); L.length = n; printf("please shu ru yuan su:\n"); for(i=1;i<=L.length;i++) scanf("%d", &L.elem[i]); } } void print(SqList L) { int i; for(i=1;i<=L.length;i++) printf("%d ", L.elem[i]); printf("\n"); } void InsertSort(SqList &L) //对顺序表L直接插入排序 { int i, j; for(i=2;i<=L.length;++i) if(L.elem[i] < L.elem[i-1]) { L.elem[0]=L.elem[i]; for(j=i-1;L.elem[j]>L.elem[0];--j) L.elem[j+1] = L.elem[j]; L.elem[j+1] = L.elem[0]; } } void BInsertSort(SqList &L) //折半插入排序 { int i, j, low, high, mid; for(i=2;i<=L.length;++i) { L.elem[0] = L.elem[i]; low = 1; high = i-1; while(low <= high) { mid = (low+high)/2; if(L.elem[0] < L.elem[mid]) high = mid-1; else low = mid+1; } for(j=i-1;j>=high+1;--j) L.elem[j+1] = L.elem[j]; L.elem[high+1] = L.elem[0]; } } int main() { SqList L; CreatList(L); print(L); //InsertSort(L); BInsertSort(L); print(L); return 0; }
插入排序 是一种对原有序列排序的方法,逐步使原序列的有序序列增长
折半插入排序 是在寻找 当前元素的位置时采取了折半查找的方法