折半插入排序(binary insertion sort)是对插入排序算法的一种改进,由于排序算法过程中,就是不断的依次将元素插入前面已排好序的序列中。由于前半部分为已排好序的数列,这样我们不用按顺序依次寻找插入点,可以采用折半查找的方法来加快寻找插入点的速度。
思路:在插入之前对前面的有序序列进行二分查找,
(1)定义变量int low=有序序列的起始索引;int high=有序序列的末尾索引;则int m = (low+high)/2;
(2)将要插入的元素与索引为m的元素比较,若小于a[m],high = m-1;反之low=m+1;
循环计算m = (low+high)/2;并重复步骤(2),直至不再满足low<=high,停止循环;
代码实现如下:
package com.test.sort; public class BinaryInsertSort { /** * 折半插入排序 * @param args */ public static void main(String[] args) { insertSort();//折半插入排序 } /** * 折半插入排序 * 思路:当执行插入第i个元素时,先将有序序列进行二分查找, * 然后将第i个元素与中间元素比较,若找到插入位置则进行插入, * 找不到继续进行二分查找,直至找到插入位置为止 */ public static void insertSort(){ int [] a = new int[]{12,123,23,1,32,45,32,34,23,348}; for (int i = 1; i < a.length; i++) { int temp=a[i]; int low = 0; int high = i-1; int j=(low+high)/2;//有序序列的中间位置 while(low<=high){ if(temp<a[j]){ high = j-1; }else{ low = j+1; } j = (low+high)/2; } //新数据插入位置low for (int m = i; m > low; m--) { a[m] = a[m-1]; } a[low] = temp; } for (int i = 0; i < a.length; i++) { if(i==a.length-1){ System.out.print(a[i]); }else{ System.out.print(a[i]+", "); } } } }
效率:
空间上只使用一个辅存单元;
时间复杂度仍为O(n²),
与直接插入排序相比,减少了元素的比较次数。