#include <stdio.h>
/*
* a example of binary insertion sort
*/
int iList[] = { 0, 99, 3, 8, 123, 4, 6, 2, 9,11 };//init a array for sort and iList[0] is not used
void BinaryInsertSort(int iList[], int iLen)//iLen is the length of iList
{
int low, high;
int i, j;
int m;
for(i = 2; i < iLen; i++)
{
iList[0] = iList[i];//save the insert number
low = 1;
high = i - 1;//because the array start from 0 , so it should be i - 1
while(low <= high)
{
m = (low + high) / 2;
if(iList[0] < iList[m])
{
high = m - 1;
}
else
{
low = m + 1;
}
}
for(j = i; j >= high + 1; --j)//high + 1 is the insert place
{
iList[j] = iList[j - 1];//backword the array number
}
iList[high + 1] = iList[0];
}
}
int main(void)
{
int i;
BinaryInsertSort(iList, 10);
for(i = 1; i < 10; i++)
{
printf(i == 9 ? "%d\n" : "%d, ", iList[i]);
}
return 0;
}
折半插入排序 一个简单示例
最新推荐文章于 2024-08-28 23:11:16 发布