【发布时间】:2020-05-01 14:19:34
【问题描述】:
我是编程新手,现在我正在研究 c++ 上的二进制搜索。当我第一次学习它时,我运行了一个二进制搜索,它运行良好,但是自从我一直试图自己复制它以来,它一直显示“对不起,我们没有找到你的号码”,当我显示返回值时,它总是返回-1(它在循环中从未改变)。我将在下面留下代码:
int main(){
int
numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
searchValue = 8,
returnValue = -1,
low = 0,
high = ARR_SIZE,
mid = (low + high) / 2;
while(low < high)
{
if(numbers[mid] == searchValue)
{
returnValue = mid;
break;
}
else if(numbers[mid] < searchValue)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
mid = (low + high) / 2;
}
if(returnValue == -1)
{
cout << "Sorry we did not find the number" << endl;
}
else
{
cout << "We found your number! It is located at index " << returnValue << endl;
}
return 0;
}
【问题讨论】:
-
这能回答你的问题吗? Binary search in C++
-
什么是
ARR_SIZE? -
试试
while (low <= high)。对于您的测试用例,最终两者都是 7,而不是找到您跳过最后一次检查的数字。
标签: c++ binary-search