二分查找用处十分广泛,一般采用非递归方法,思路很简单;
#include<stdio.h>
#include<string.h>
int main()
{
int x;
scanf("%d",&x);
int mid,left,right;
int a[20] = {1,2,3,4,5,6,7,8,10,15,79};
left = 0;
right = 10;
while(left <= right)
{
mid = (left + right)/2;
if(x == a[mid])
{
printf("%d",mid+1);
break;
}
else if(a[mid] > x)
{
right = mid - 1;
}
else if(a[mid] < x)
{
left = mid + 1;
}
else
{
printf("没找到此数");
break;
}
}
}