折半插入排序的基本思想和直接插入排序的一样,区别在于寻找插入位置的方法不同,折半插入排序是采用折半查找法来寻找插入位置的。
#include <iostream>
using namespace std;
#define MAX 100
void BinaryInsertSort(int R[], int n);
int main()
{
int n;
int R[MAX];
while(cin >> n)
{
for(int i = 0; i != n; i++)
cin >> R[i];
BinaryInsertSort(R, n);
for(i = 0; i != n; i++)
cout << R[i] << " ";
cout << endl;
}
return 0;
}
void BinaryInsertSort(int R[], int n)
{//折半插入排序,R[]为待排序数组,n为元素个数
int i, j;
int low, high, middle;
int temp;
for(i = 1; i != n; i++)
{//R[0]是一个数,自然有序,所以从R[1]开始
low = 0;
//已排序区的第一个位置下标始终为0
high = i-1;
//已排序区的最后一个位置下标为待排序元素下标减1
temp = R[i];
//temp记录当前待排序元素
while(low <= high)
{//折半查找找出待排序元素的插入位置
middle = (low + high) / 2;
if(temp > R[middle])
low = middle+1;
//如果当前元素大于中间元素则应在已排序区序列的右半区
else
high = middle-1;
//否则在左半区
}//当low大于high时跳出while,则位置在high+1处
for(j = i-1; j >= high+1; j--)
R[j+1] = R[j];
//移动已排序序列的high+1后面的元素
R[j+1] = temp;
//插入元素
}
}