#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;
}折半插入排序 一个简单示例
最新推荐文章于 2025-10-24 17:19:14 发布
本文介绍了一种改进的插入排序算法——二分插入排序,并通过C语言实现。该算法利用二分查找法来减少比较次数,提高排序效率。示例代码展示了如何对一个整数数组进行排序。
9305

被折叠的 条评论
为什么被折叠?



