我几个小时以来一直在努力。我不知道我做错了什么。它检查气泡排序的数组以查找用户输入的数字。我已经设置打印出数字,所以我可以输入一个我确定在数组中的数字,但是当我输入一个我看到的数字时,它几乎总是返回false。有时是真的,但通常是假的。我不确定我做错了什么。 我设置打印出这样的数字:数字索引 -
非常感谢你的帮助。
int main()
{
int randomArray[20];
int searchValue;
//Irrelevant code snippet: Functioning code fills an array with random numbers between 0-60 and
//bubble sorts them. User inputs searchValue.
if(binarySearch(randomArray, searchValue, randomArray[0], randomArray[19]))
{
cout<<"The number you've searched for is in the array.";
}
else
{
cout<<"The number you've searched for is currently not in the array.\n";
}
return 0;
}
bool binarySearch(int arr[], int searchValue, int low, int high)
{
while(low<=high)
{
int middle = (low+high)/2;
if(arr[middle] == searchValue)
return true;
else if (arr[middle] > searchValue)
high = middle - 1;
else
low = middle + 1;
}
return false;
}
答案 0 :(得分:1)
你的电话应该是
binarySearch(randomArray, searchValue, 0, 19);