排序算法:折半插入排序
前提:一个基本条件就是序列已经有序
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
void InsertSort(vector<int>& R, int num)
{
int n = R.size();
R.resize(n + 1);
int left = 0;
int right = 5;
while (left <= right)
{
int middle = (left + right) / 2;
if (num < R[middle])
{
right = middle - 1;
}
else
{
left = middle + 1;
}
}
//num插入到high位置之后
for (int i = n - 1; i >= right + 1; i--)
{
R[i + 1] = R[i];
}
//num归位
R[right + 1] = num;
}
int main()
{
vector<int> nums = { 13, 38, 49, 65, 76, 97 };
InsertSort(nums, 27);
InsertSort(nums, 49);
system("pause");
return 0;
}
时间复杂度:最好为O(nlogn),最坏O(nn),平均O(nn)
空间复杂度:O(1)