<分区>
我已经为此苦苦挣扎了几个小时。我不知道我做错了什么。它检查用户输入数字的冒泡排序数组。我将它设置为打印出数字,这样我就可以输入一个我确定在数组中的数字,但是当我输入一个我看到的数字时,它几乎总是返回 false。有时是真的,但通常是假的。我不确定我做错了什么。 我将其设置为打印出这样的数字:number-index-
非常感谢大家的帮助。
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;
}