版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xh_xinhua/article/details/62422971
#include <stdio.h>
#define n 10
int main()
{
int left = 0;
int right = n-1;
int a[n];
int i, mid, key;//key 是要查找的数字;mid 表示中间值
printf("input the key number\n");
scanf("%d",&key);
printf("input ten number\n");
for(i =0; i < n; i++)
{
scanf("%d",&a[i]);
}
while(left <= right)
{
mid = (left + right)/2;
if(key == a[mid])
{
break;
}
else if(key > a[mid])
left = mid + 1;//要找的数可能在中上,右值不变,左值移到中间再 + 1
else
right = mid - 1;//要找的数可能在中下,左值不变,右值移到中间再 - 1
}
if(left > right)//不在区间内
{
printf("it is not find the key\n");
return -1;
}
else
{
printf("mid =%d\n", mid);
}
return 0;
}