二进制搜索C++
Binary Search C++
我已经为此挣扎了几个小时。我不知道我做错了什么。它检查气泡排序数组中用户输入的数字。我把它设置为打印出数字,这样我就可以输入一个我确信在数组中的数字,但当我输入我看到的数字时,它几乎总是返回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);
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 在C++中搜索嵌套多映射值
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- 为什么二进制搜索在我的测试中不起作用
- 正在尝试重载二进制搜索树分配运算符
- c++binary_search函数排序数组(流行名称搜索)出现问题
- 向量上的线性搜索
- 如何在动态数组上使用搜索函数
- 对于MacOS上的G++,如何添加默认的include目录/usr/local/include和默认的库搜索路径/usr
- cmake:添加要搜索头文件的目录
- 使用C++创建特殊的二叉搜索树
- 在C++的字符串中搜索和删除某些字符
- std::unordered_map 搜索算法是如何实现的?
- 使用不变量来确定二分搜索中的边界条件
- 二叉搜索如何比线性搜索更快?
- 按边长度递归搜索图中所有可行路径
- QStackWidget - 按名称搜索
- 在递归二叉搜索树中搜索
- 我的二进制搜索程序只是关闭了