折半插入排序是對直接插入排序的改進算法,又稱爲二分法插入排序,折半搜索要比順序搜索快,所以就平均性能來說要比直接插入排序快,下面附上代碼
import java.util.Scanner;
import org.junit.Test;
public class Main2 {
/**
* 折半插入排序
* @param a 待排序數組
* @return 排好序數組
*/
public static int[] binaryInsertSort(int[] a) {
int left = 0;// 數組左邊界下標
int right = a.length - 1;// 數組右邊界下標
for (int i = left + 1; i <= right; i++) {
int temp = a[i];
int low = left;
int middle;
int high = i - 1;// low到high爲排好序區間
while (low <= high) {// 利用折半搜索插入位置
middle = (low + high) / 2;// 取中點
if (temp < a[middle]) {// 插入值小於中點值
high = middle - 1;// 向左縮小區間
} else {
low = middle + 1;// 向右縮小區間
}
}
for (int k = i - 1; k >= low; k--) {// 成塊移動,空出插入位置
a[k + 1] = a[k];
}
a[low] = temp;// low即爲插入位置
}
return a;
}
@Test
public void testBinaryInsertSort() {
Scanner sc = new Scanner(System.in);
System.out.println("請輸入數組長度!");
int n = sc.nextInt();
int[] a = new int[n];
System.out.println("請輸入數組元素");
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
}
int[] result = binaryInsertSort(a);
for (int i = 0; i < result.length; i++) {
System.out.print(result[i] + " ");
}
}
}