1 基本思想
折半插入排序(binary insertion sort)的基本原理與直接插入排序相同,不同之處在於,確定當前記錄在前面有序子數組中的位置時,直接插入排序是採用順序查找的方法,而折半插入排序是採用折半查找的方法,因此它僅適用於順序存儲的線性表。
2,算法的實現(Java)
package Algorithm;
public class binary_insert_sort {
/**
* @param args
*/
public static void main(String[] args) {
int array[] = {23,12,34,56,78,67,99,100};
System.out.println("---------排序前的結果----------");
binary_insert_sort.output(array);
System.out.println("---------排序後的結果----------");
binary_insert_sort.binary_insert_sort(array);
binary_insert_sort.output(array);
}
//折半插入排序算法
public static void binary_insert_sort(int[] arr){
int low,high,mid,temp,j;
for(int i=1;i<arr.length;i++){
temp = arr[i];
low = 0;
high = i-1;
while(low <=high){
mid =(high+low)/2;
if(arr[mid] > temp){
high = mid -1;
}
else
{
low = mid+1;
}
}
for(j = i-1;j >=high+1; j--)
arr[j+1] = arr[j];
arr[j+1] = temp;
}
}
//輸出打印
public static void output(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+",");
}
System.out.println();
}
}
得到的結果如下所示:
3,性能分析
折半查找只是減少了比較次數,但是元素的移動次數不變。因此,它的
空間複雜度 O(1) ,時間複雜度O(n^2),是一種穩定的排序算法