您的位置:首页 > 其它

折半插入排序 一个简单示例

2013-03-03 23:39 344 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: