我正在迭代地实现二分搜索,并且我正在数组中搜索查找数据。
#include<stdio.h>
int main()
{
int arr[10] = {2,3,4,5,6,7,8,9,10,11};
int find = 12;
int size = 10;
int pos = 0;
int mid;
while(pos<=size)
{
mid = pos+(size-pos)/2;
printf("mid = %d %d\n",mid,arr[mid]);
if(arr[mid] == find){
printf("mid = %d %d\n",mid,arr[mid]);
return printf("position is %d\n",mid+1);
}
if(arr[mid]< find)
pos = mid+1;
else
size = mid-1;
}
printf("data not found\n");
return 0;
}
但是当我尝试查找高于 arr 中给出的最大值的任何数据时,我的代码失败了。 我正在使用代码块来编译和运行我的代码。
最佳答案
数组从索引 0 开始,迭代时会迭代到 n-1 个元素。你的循环:
while(pos<=size)
应改为
while(pos<size)
因此它不会超出您尚未定义的元素。
关于c - 二分查找时上限失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28007704/