c++ - 二进制搜索 C++

标签 c++ binary-search

<分区>

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

最佳答案

你的电话应该是这样的

binarySearch(randomArray, searchValue, 0, 19);

关于c++ - 二进制搜索 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25799807/

相关文章:

c++ - 使用模板特化和接口(interface)对实例和原始类型进行统一函数调用

c++ - VS 2012 不构建依赖项目

c++ - 服务器设置在编译时保持打印 "connected"即使没有客户端连接

python - 我的递归二分搜索程序出了什么问题?

.net - 如何对 IList<T> 执行二分查找?

java - 我的java二进制搜索代码有什么问题?

c++ - 数据结构与 yaml-cpp 接口(interface)的设计技巧?

c++ - std::valarray 和 std::array 有什么区别

c++ - 对属性进行 binary_search 的编译错误

c++ - 通过修改二进制搜索算法来改进它,使其在大量单词(单词列表)中搜索单词时工作得更快