2019-08-07
代码实现
/**
* @Date: 2019/8/7 09:08
* @Description: 折半插入排序,对直接插入排序中
* i前面的基本有序序列使用折半查找来寻找合适的插入位置
*/
public class BinsertSort {
public void binsertSort(int[] a) {
int length = a.length;//数组长度,将这个提取出来是为了提高速度
int insertNum;//要插入的数
//i从第二个数开始向后遍历
for (int i = 1; i < length; i++) {
insertNum = a[i];//要插入的数
//对i前面的序列进行折半查找,找出插入位置
int low = 0, high = i - 1;
while (low <= high) { //比较,折半查找寻找合适的插入位置low
int mid = (low + high) / 2;
if (insertNum < a[mid])//插入到在低半区
high = mid - 1;
else //插入到在高半区
low = mid + 1;
}
//将插入位置low之后的元素向后移动
for (int j = i - 1; j >= low; --j)
a[j + 1] = a[j];
a[low] = insertNum;//将要插入的数插入到合适的位置
}
System.out.println(Arrays.toString(a));
}
@Test
public void testBinsertSort() {
int[] a = {35, 11, 24, 52, 77, 69, 8, 3, 6, 62};
int[] b = {7, 9, 3, 2, 5, 8, 6};
binsertSort(a);
binsertSort(b);
}
}
/*
Output:
[3, 6, 8, 11, 24, 35, 52, 62, 69, 77]
[2, 3, 5, 6, 7, 8, 9]
*/