c++ - 更正我的二进制搜索索引和超出范围的数组
问题描述
#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; // Line 1
int myarr[size]; // Line 2
cin>> size; // Line 3
让我们逐步执行代码。
- size = 0,myarray 还不存在。
- size 仍然 = 0,myarray 的长度为 0。
- 现在无论用户输入什么大小(可能是 5),但 myarray 的长度仍然为 0。
您需要交换第 2 行和第 3 行。
现在,补充一点——可变长度数组不是标准的 C++。无论如何,很多编译器都会处理它们,但使用它被认为是错误的。
大多数人会告诉你使用:
#include <vector>
...
std::vector<int> myArray;
但这更复杂。你也可以这样做:
int * myArray = new int[size];
...
// When done:
delete myArray;
如果您不打算使用 std::vector<>,这是正确的方法。
推荐阅读
- java - JAVA笛卡尔形状绘图仪
- c++ - 不能使用 MinGW 包含 SDL_ttf.h
- windows - 某些 Windows 10 应用程序中的按钮在悬停时会随机改变颜色
- java - 如何在没有 android studio 的情况下创建 sfb 文件
- java - Centos 上的堆内存问题
- linux - docker 无法在外部设备上统计目录
- java - 从 textview 获取值
- html - 设置分隔符剪辑路径(多边形)响应
- javascript - 未捕获(承诺中)ReferenceError:纬度未定义
- maven - 是否有使用 CI jenkins 管道(最好是 maven+nexus)构建铬扩展(Edge+Chrome)的最新(crx3)方法?