为什么二进制搜索在我的测试中不起作用

Why binary search is not working on my test?

本文关键字:测试 不起作用 我的 二进制 搜索 为什么      更新时间:2023-10-16

我刚刚用数组在c++上编写了一个二进制搜索,但它并不适用于我的所有测试。

#include <iostream>
using namespace std;
int bSearch(int arr[], int item);
int main() {
int testArr[] = {1, 3, 5, 7, 9, 10, 12, 13, 15, 16, 18, 20};
int result = bSearch(testArr, 18);
cout << "The result of binary search is " << result << endl;
return 0;
}
int bSearch(int arr[], int item) {
int start = 0;
int middle(0), guess(0);
int finish = sizeof(arr);
while(start <= finish) {
middle = (start + finish) / 2;
guess = arr[middle];
if(guess == item)
return middle;
else if(guess > item)
finish = middle - 1;
else
start = middle + 1;
}
return -1;
}

你能解释一下为什么会这样吗?

bSearch中,参数arr不是数组,而是指向int的指针。没有关于它是否指向int数组的信息,或者元素的数量可能是这样一个数组的一部分。因此sizeof(arr)将是指针的大小(通常为4或8(。

您需要将数组中包含的元素数传递给bSearch,或者使用一个跟踪大小的标准容器(std::vectorstd::array(。