版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010095372/article/details/84258448
在直接插入的时候,为了给被插入值找到合适的位置,就比较一次,直接决定其往挪走还是不走,比较➕移动,就是两次了。
折半将比较和移动分离,先折半找出位置再统一移动。
和直接插入一样的,仅仅优化了找位置的算法。
void InsertSort(int a[], int n) {
int i, j, low, high, mid, temp;
for (i = 1; i < n; i++) {
temp = a[i];
//找合适的位置,用折半找,就是二分法
low = 0;
high = i-1;
while (low <= high) {
mid = (low + high)/2;
if(a[mid] > temp)
high = mid - 1;
else
low = mid + 1;
}
//找到位置一样的操作
for (j = i-1; j >= high+1; --j) {
a[j+1] = a[j];
}
a[high+1] = temp;
}
}
5260391748
2560391748
2560391748
0256391748
0235691748
0235691748
0123569748
0123567948
0123456798
0123456789