基本思想为:先折半查找出元素的待插入位置,然后再统一移动待插入位置之后的所有元素
折半查找排序是稳定的排序
#include "stdio.h"
void PrintfArray(int* ar, int left,int right)
{
for (int i = left; i < right; i++)
printf("%d ", ar[i]);
}
void BinarySort(int* ar, int left, int right)
{
for (int i = left + 1; i < right; i++)
{
int tmp = ar[i];
int low = left;
int high = i - 1;
while (low<=high)
{
int mid = (low + high) / 2;
if (tmp < ar[mid])
high = mid - 1;
else
low = mid + 1;
}
for (int j = i; j > low; j--)
ar[j] = ar[j - 1];
ar[low] = tmp;
}
}
int main()
{
int ar[] = {13,37,34,78,90,88,12 };
int n = sizeof(ar) / sizeof(ar[0]);
PrintfArray(ar, 0, n);
BinarySort(ar, 0, n);
printf("\n");
PrintfArray(ar, 0, n);
}