排序算法-折半插入排序
关键点
- 理解二分查找的具体过程
- 理解要插入位置后面的数据移动过程
#include <iostream>
#include <vector>
using namespace std;
vector<int> halfInsert(vector<int> arr) {
int high, low, mid, temp;
for (int i = 1; i < arr.size(); i++) {
high = i-1;
low = 0;
mid = 0;
while (low <= high) {
temp = arr[i];
mid = (high + low) / 2;
if (arr[i] < arr[mid])
high = mid - 1;
else low = mid + 1;
}
for (int j = i-1; j >= high+1; j--) {
arr[j + 1] = arr[j];
}
arr[high+1] = temp;
}
return arr;
}
void test() {
vector<int> arr= { 5, 2, 11, 56, 1, 33, 22, 15, 24, 30 };
auto ret = halfInsert(arr);
for (auto it = ret.begin(); it != ret.end(); it++) {
cout << *it << " ";
}
}
int main() {
test();
return 0;
}