#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;
}
折中查找(二分查找)
最新推荐文章于 2022-11-17 15:04:56 发布