相比起直接插入排序,折半插入排序减少了关键字的比较次数,而记录的移动次数不变,因此折半插入排序的时间复杂度仍然为O(n^2)

稳定性:稳定

void BInsertSort(int a[], int size) 
{
int i, j, low = 0, high = 0, mid;
int temp = 0;
for (i = 1; i < size; i++)
{
low = 0;
high = i - 1;
temp = a[i];
//采用折半查找法判断插入位置,最终变量 low 表示插入位置
while (low <= high)
{
mid = (low + high) / 2;
if (a[mid] > temp)
{
high = mid - 1;
}
else {
low = mid + 1;
}
}
//有序表中插入位置后的元素统一后移
for (j = i; j > low; j--) {
a[j] = a[j - 1];
}
a[low] = temp;//插入元素
}
}

完整代码

#include <iostream>
#include <windows.h>
using namespace std;

void PrintArray(int *Array, int iSize)
{
for (int i = 0; i < iSize; i++)
{
cout << "Key is " <<i<<" Current Value is " << Array[i] << endl;
}
}
void BInsertSort(int a[], int size)
{
int i, j, low = 0, high = 0, mid;
int temp = 0;
for (i = 1; i < size; i++)
{
low = 0;
high = i - 1;
temp = a[i];
//采用折半查找法判断插入位置,最终变量 low 表示插入位置
while (low <= high)
{
mid = (low + high) / 2;
if (a[mid] > temp)
{
high = mid - 1;
}
else {
low = mid + 1;
}
}
//有序表中插入位置后的元素统一后移
for (j = i; j > low; j--) {
a[j] = a[j - 1];
}
a[low] = temp;//插入元素
}
}
int main()
{
int a[10] = { 9,10,8,7,6,5,4,3,2,1 };
BInsertSort(a,10);

PrintArray(a,10);
system("pause");
return 0;
}