在插入数据时,用二分查找法查找数据,而不是一一比较。
意外收获:
条件:数据从小到大,假设a[a.length]为无穷大。二分查找时,找不到,则左右索引最后相等,目标数据会比当前索引指向的数据小。
public static void insertSortWithBinarySearch(int[] a) {
if (a == null) {
return;
}
for (int out = a.length - 1; out > 0; out--) {
int tempValue = a[out - 1];
int leftDex = out;
int rightDex = a.length;
int mid = 0;
while (leftDex < rightDex) {
mid = (leftDex + rightDex) >>> 1;
if (tempValue > a[mid]) {
leftDex = mid + 1;
} else if (tempValue < a[mid]) {
rightDex = mid;
} else {
// 可以有重复的数据,但是不保证重复数据的先后位置(不稳定的)
break;
}
}
int sDex = 0;
// 没找到,这时 leftDex==rightDex is true,插入的数据一定比索引为leftDex的数小
if (leftDex == rightDex) {
sDex = leftDex;
} else {
// 找到与这个数据相同的数据,放在其左或右从结果来看都是一样的
sDex = mid;
}
for (int i = out; i < sDex; i++) {
a[i - 1] = a[i];
}
a[sDex - 1] = tempValue;
}
}