拆半插入排序是对直接插入排序的简单改进,对于直接插入排序而言,当第i-1趟需要将第i个元素插入前面的0~i-1个元素序列中,它总是从i-1个元素开始,逐个比较每个元素,知道找到它的位置。这显然没有利用前面0~i-1个元素已经有序的特点,而拆半插入排序则改进这一点。
import java.util.Arrays;
/**
* @author stefanie zhao
* @date 2014-10-11 上午11:05:53
*/
public class BinaryInsertSort {
public static void main(String[] args) {
DataWrap[] data = { new DataWrap(23, ""), new DataWrap(13, ""), new DataWrap(43, ""), new DataWrap(9, ""),
new DataWrap(3, ""), new DataWrap(34, "") };
System.out.println("before sort: \n" + Arrays.toString(data));
binaryInsertSort(data);
System.out.println("after sort: \n" + Arrays.toString(data));
}
public static void binaryInsertSort(DataWrap[] data) {
System.out.println("begin sort....");
int arrayLength = data.length;
for (int i = 1; i < arrayLength; i++) {
DataWrap tmp = data[i];
int low = 0;
int high = i - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (tmp.compareTo(data[mid]) > 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
// 将low到i处的所有元素向后整体移动一位
for (int j = i; j > low; j--) {
data[j] = data[j - 1];
}
// 最后将tmp的值插入合适位置
data[low] = tmp;
System.out.println(Arrays.toString(data));
}
}
}
执行结果:
before sort:
[23, 13, 43, 9, 3, 34]
begin sort....
[13, 23, 43, 9, 3, 34]
[13, 23, 43, 9, 3, 34]
[9, 13, 23, 43, 3, 34]
[3, 9, 13, 23, 43, 34]
[3, 9, 13, 23, 34, 43]
after sort:
[3, 9, 13, 23, 34, 43]
上面的程序的排序效果和直接插入排序的效果是基本相同的,只是更快了些,因为拆半插入排序可以更快的确定第i个元素的插入位置。