实现从键盘输入一个整数b,在数组a中采用二分法查找该数并输出下标,若未找到则输出-1。 例如,输入13输出8 输入-1,输出1 输入19,输出-1
#include <stdio.h>
#define N 10
void main(void)
{
int a[N] = {-2, -1, 0, 1, 3, 4, 7, 9, 13, 17};
int i,low=0,high=N-1,mid,ret=-1;
int key;
//输入数据
scanf("%d",&key);
while(low <= high)
{
mid = low + (high-low)/2;
if(a[mid] == key)
{ret=mid;break;}
else if(a[mid] > key)
{high=mid-1;continue;}
else
{low=mid+1;continue;}
}
printf("%d ",ret);
}