排序算法(二)二分插入排序
2021-11-04 本文已影响0人
又语
二分插入排序是在插入排序的基础上引入 二分查找 的思想。
复杂度分析
- 最坏情况:
O(n²)
- 最好情况:
O(nlog2n)
- 平均:
O(log2n)
Java 代码实现
import java.util.Arrays;
public class BinarySort {
public static void sort(int[] data) {
int temp;
int low;
int high;
int middle;
for (int i = 1; i < data.length; i++) {
temp = data[i];
low = 0;
high = i - 1;
while (low <= high) {
middle = (low + high) / 2;
if (temp < data[middle]) {
high = middle - 1;
} else {
low = middle + 1;
}
}
for (int j = i - 1; j >= low; j--) {
data[j + 1] = data[j];
}
if (i != low) {
data[low] = temp;
}
System.out.println(Arrays.toString(data));
}
}
public static void main(String[] args) {
int[] a = {34, 24, 93, 1, 32, 98, 18, 39};
sort(a);
}
}
运行结果
[24, 34, 93, 1, 32, 98, 18, 39]
[24, 34, 93, 1, 32, 98, 18, 39]
[1, 24, 34, 93, 32, 98, 18, 39]
[1, 24, 32, 34, 93, 98, 18, 39]
[1, 24, 32, 34, 93, 98, 18, 39]
[1, 18, 24, 32, 34, 93, 98, 39]
[1, 18, 24, 32, 34, 39, 93, 98]