折半查找算法
Posted tedani
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了折半查找算法相关的知识,希望对你有一定的参考价值。
#include <stdio.h>
int halfIntervalSearch(int *p, unsigned int len, int num)
{
unsigned int highSN = len-1;
unsigned int lowSN = 0;
unsigned int midSN = 0;
int ret = -1;
//lowSN与highSN折半法无限靠近,直至lowSN==highSN找到。
//一旦找不到,则当lowSN==highSN后,lowSN继续+1 or highSN继续-1,直到lowSN > highSN退出
while (lowSN <= highSN)
{
midSN = (lowSN + highSN)/2;
if (num == p[midSN])
{
ret = midSN;
break;
}
else if (num > p[midSN])
{
lowSN = midSN + 1;
}
else if (num < p[midSN])
{
highSN = midSN - 1;
}
}
return ret;
}
void main(void)
{
int numberTable[] = {2,47};
int sn = -1;
sn = halfIntervalSearch(numberTable, sizeof(numberTable)/sizeof(int), 47);
printf("find sn number: %d
", sn);
}
以上是关于折半查找算法的主要内容,如果未能解决你的问题,请参考以下文章