折半插入排序和直接插入排序是一样的。都是把未定位的元素插入到已排好序的数组里。不同的是对插入位置的查找方法不同。直接插入是比较关键字一次,插入一次。折半插入是折半二分比较得到最终插入位置后,集体移动数组元素,空出待插入位置,再插入新的元素。
还有一个难点就是折半查找后,对最终插入位置的下标的确定。需要仔细思考,对照,因为仅差一位。
全部代码如下:
#include<iostream>
using namespace std;
void binaryInsertSort(int array[],int length) {
int temp, indexSmall, indexLarge,indexMid;
for (int i = 1; i < length; i++) {
temp = array[i];
indexSmall = 0;
indexLarge = i - 1;
while (indexSmall <= indexLarge){
indexMid = (indexSmall + indexLarge) / 2;
if (temp > array[indexMid])
indexSmall = indexMid + 1;
else
indexLarge = indexMid - 1;
} // 进过仔细比对,插入位置是 indexSmall
for (int j = i; j >= indexSmall + 1; j--)
array[j] = array[j - 1];
array[indexSmall] = temp;
}
for (int i = 0; i < length; i++)
cout << array[i] << ' ';
}
int main() {
int array[] = { 1,5,2,4,6,3,0,7,9,8 }, length = 10;
binaryInsertSort(array,length);
return 0;
}
测试结果如下:
谢谢阅读。