【发布时间】:2021-12-27 15:28:10
【问题描述】:
#include <iostream>
using namespace std;
int binarySearch(int arr[], int b, int e, int number) {
while (b <= e) { //This loop will keep going until b (first elememt) is less than or equal to (last element)element
int c = (b+e)/ 2;
if (arr[c] == number) {
return c;
} else if (arr[c] <= number) { //if c less than number entered the loop will keep adding 1 to c and making it become b (first element)
b = c + 1; //until the condition is no longer true
} else {
e = c - 1;
}
}
return -1;
}
int main() {
int size=0;
int myarr[size];
cin>> size;
int num;
int output;
for (int i = 0; i <= size; i++) {
cin >> myarr[i];
}
cin >> num;
output = binarySearch(myarr, 0, size, num);
if (output == -1) {
cout<<-1;
}
else {
cout << output;
}
return 0;
}
我需要有人来纠正我的代码,以便二进制搜索给出数组中元素的索引并告诉我我犯的错误,因为我现在很困惑
【问题讨论】:
-
二进制搜索仅适用于排序数组(在您的情况下为升序)。你是按升序插入数字吗?
-
请注意,
int size=0; int myarr[size];是一个 VLA,标准 C++ 中不存在这些。您还首先创建大小为0的数组,然后在创建数组后询问用户数组应该有多大。 -
是的,我按升序插入数字,但我似乎仍然无法找出错误
-
@Keith 你看到我指出的错误了吗?
-
@Keith 程序中的事情按照您编写它们的顺序发生。如果你创建一个大小为 0 的数组,然后问用户这个数组应该有多大,你认为现在的数组有多大?