二进制搜索C++

Binary Search C++

本文关键字:C++ 搜索 二进制      更新时间:2023-10-16

我已经为此挣扎了几个小时。我不知道我做错了什么。它检查气泡排序数组中用户输入的数字。我把它设置为打印出数字,这样我就可以输入一个我确信在数组中的数字,但当我输入我看到的数字时,它几乎总是返回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;
}

您的呼叫应该像一样

binarySearch(randomArray, searchValue, 0, 19);