算法
??折半插入排序是直接插入排序與折半查找二者的結合,仍然是將待排序元素插入到前面的有序序列,插入方式也是由后往前插,只不過直接插入排序是邊比較邊移位。而折半插入排序則是先通過折半查找找到位置后再一并移位,最終將待排序元素賦值到空出位置。
??前面提到過折半插入排序是對直接插入排序的優(yōu)化,其實只是相對地使用折半查找比較次數(shù)變少了,每趟比較次數(shù)由o(n)變成了o(log2(n))。然而并沒有真正改變其效率,時間復雜度依然是o(n*n)。在所有內排序算法中依然是平均效率比較低的一種排序算法。
例子
依然以序列4,3,1,2,5為例
示例
Codes
package com.fairy.InnerSort;
import java.util.Scanner;
/**
* 折半插入排序
* @author Fairy2016
*
*/
public class BinaryInsertSort {
public static void sort(int a[], int n) {
int i, j;
for(i = 2; i <= n; i++) {
if(a[i] < a[i-1]) {
a[0] = a[i];
//這里與直接插入排序不同,先找到位置再一并移位
int low = 1;
int high = i-1;
//折半查找
while(low <= high) {
int mid = (low+high)/2;
if(a[mid] < a[0]) {
low = mid + 1;//位置在右半邊
} else {
high = mid - 1;//位置在左半邊
}
}
//low = high+1時循環(huán)結束,即位置為low
//一并移位
for(j = i-1; j >= low; j--) {
a[j+1] = a[j];
}
a[j+1] = a[0];//賦值
}
}
}
public static void Print(int a[], int n) {
for(int i = 1; i <= n; i++) {
System.out.print(a[i]+" ");
}
}
public static void main(String args[]) {
int n;
int a[];
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()) {
n = scanner.nextInt();
if(n > 0) {
a = new int[n+1];
for(int i=1; i <= n; i++) {
a[i] = scanner.nextInt();
}
sort(a, n);
Print(a, n);
}
}
}
}