基本概念
折半插入排序(binary insertion sort)是对插入排序算法的一种改进,由于排序算法过程中,就是不断的依次将元素插入前面已排好序的序列中。由于前半部分为已排好序的数列,这样我们不用按顺序依次寻找插入点,可以采用折半查找的方法来加快寻找插入点的速度。
算法思想
在将一个新元素插入已排好序的数组的过程中,寻找插入点时,将待插入区域的首元素设置为a[low],末元素设置为a[high],则轮比较时将待插入元素与a[m],其中m=(low+high)/2相比较,如果比参考元素大,则选择a[low]到a[m-1]为新的插入区域(即high=m-1),否则选择a[m+1]到a[high]为新的插入区域(即low=m+1),如此直至low<=high不成立,即将此位置之后所有元素后移一位,并将新元素插入a[high+1]。
稳定性及复杂度
折半插入排序算法是一种稳定的排序算法,比直接插入算法明显减少了关键字之间比较的次数,因此速度比直接插入排序算法快,但记录移动的次数没有变,所以折半插入排序算法的时间复杂度仍然为O(n^2),与直接插入排序算法相同。附加空间O(1)。
实现代码:
1 #include<stdio.h> 2 #include<string.h> 3 #include<math.h> 4 #include<ctype.h> 5 #include<stdbool.h> 6 #include<stdlib.h> 7 8 void BinaryInsertSort(int *a, int n) 9 { 10 int i,j,k,low,high,m; 11 for(i = 1; i < n; i++) { 12 low = 0; 13 high = i - 1; 14 15 while(low <= high) { 16 m = (low + high) / 2; 17 if(a[m] > a[i]) high = m - 1; 18 else low = m + 1; 19 } 20 21 if(j != i - 1) { 22 int temp = a[i]; 23 for(k = i - 1; k >= high + 1; k--) 24 a[k + 1] = a[k]; 25 a[k + 1] = temp; 26 } 27 } 28 } 29 30 void printArray(int *a, int n) 31 { 32 for(int i=0; i<n; i++){ 33 printf("%d ",a[i]); 34 35 } 36 printf("\n"); 37 } 38 39 int main() 40 { 41 int a[7]={5,2,1,8,10,23,22}; 42 BinaryInsertSort(a,7); 43 printArray(a,7); 44 return 0; 45 }