如何在二进制搜索中获得一个大的十进制数组



我目前正在尝试完成一个项目。这段代码只是我一直在使用的二进制搜索算法。这是我做过的第一个搜索算法,因为我是一个自学成才的程序员,我需要一些关于如何让它发挥作用的建议。我使用QT创建者作为IDE。

我的代码中没有任何错误。然而,当我运行代码时,答案总是";未找到匹配项";。我认为这与数组本身有关,因为我之前用10个整数测试过它,效果非常好。

我知道我不太善于解释,因为我的英语很差。但如果你有任何问题,请回复我。

用C++编写的代码

#include <iostream>
using namespace std;
float binarySearch(float arr[], int left, int right, float x)
{
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] == x)
{
return mid;
}
else if (arr[mid] < x)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}
int main()
{
float num;
float output;
float myarr[100] = {44.64978683, 44.62352548, 44.5972165, 44.57086043, 44.54445783,
44.51800925, 44.49151522, 44.46497629, 44.43839299, 44.41176587,
44.38509546, 44.35838228, 44.33162687, 44.30482976, 44.27799146,
44.25111251, 44.22419342, 44.1972347, 44.17023688, 44.14320046,
44.11612596, 44.08901388, 44.06186473, 44.03467901, 44.00745722,
43.98019985, 43.95290742, 43.9255804, 43.89821929, 43.87082457,
43.84339674, 43.81593628, 43.78844366, 43.76091937, 43.73336389,
43.70577768, 43.67816122, 43.65051497, 43.62283941, 43.595135,
43.56740221, 43.53964148, 43.51185328, 43.48403806, 43.45619628,
43.42832838, 43.40043481, 43.37251603, 43.34457246, 43.31660456,
43.28861275, 43.26059748, 43.23255917, 43.20449827, 43.17641519,
43.14831036, 43.12018421, 43.09203716, 43.06386963, 43.03568203,
43.00747477, 42.97924828, 42.95100295, 42.92273919, 42.89445742,
42.86615803, 42.83784141, 42.80950798, 42.78115811, 42.75279222,
42.72441067, 42.69601387, 42.6676022, 42.63917604, 42.61073577,
42.58228177, 42.55381441, 42.52533407, 42.49684112, 42.46833593,
42.43981886, 42.41129027, 42.38275054, 42.35420001, 42.32563904,
42.29706799, 42.26848721, 42.23989705, 42.21129785, 42.18268996,
42.15407372, 42.12544947, 42.09681755, 42.06817829, 42.03953203,
42.01087909, 41.98221981, 41.9535545, 41.9248835, 41.89620711};
while(true)
{
cout << "Please enter an element to search" << endl;
cin >> num;
output = binarySearch(myarr, 0, 100, num);
if (output == -1)
{
cout << "No Match Found" << endl;
}
else
{
cout << "Match found at position: " << output << endl;
}
}
}

数组myarr的元素按递减顺序排序,因此当当前元素大于目标而不是小于目标时,left应设置为mid+1

错误:

else if (arr[mid] < x)

正确:

else if (arr[mid] > x)

此外,该数组只有100个元素,因此初始right应该是99,而不是100

错误:

output = binarySearch(myarr, 0, 100, num);

正确:

output = binarySearch(myarr, 0, 99, num);

最新更新