所谓二分查找就是就是拿要查找的元素s与一个有序序列中最中间的那个元素m比较,如果m==s.查找结束,如果m>s,则对最小元素到m之间的序列再次进行二分查找,如果m<s,则对m到最大元素之间的序列再次进行二分查找,原理如此,转换成代码如下:
#include <stdio.h>
int bs(int a[],int length,int x )
{
printf("suppose your array is ascending order\n");
int LowIndex=0,HighIndex=length-1,middle=0;
if(x>a[HighIndex]||x<a[LowIndex])
return -1;
while(LowIndex<=HighIndex)
{
middle=LowIndex+(HighIndex-LowIndex)/2;
if(a[middle]==x)
return middle;
else if(a[middle]>x)
{
HighIndex=middle-1;
}
else
{
LowIndex=middle+1;
}
}
return -1;
}
int main(void)
{
int x,a[]={1,2,3,5,6,7,8,9,10,11};
scanf("%d",&x);
printf("The searching result is %d\n",bs(a,10,x));
return 0;
}