首页 > 解决方案 > 更正我的二进制搜索索引和超出范围的数组

问题描述

   #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;
}

我需要有人来纠正我的代码,以便二进制搜索给出数组中元素的索引并告诉我我犯的错误,因为我现在很困惑

标签: c++arrayssortinghelper

解决方案


泰德给了你答案,但我会进一步说明。这是你的代码:

int size=0;       // Line 1
int myarr[size];  // Line 2
cin>> size;       // Line 3

让我们逐步执行代码。

  1. size = 0,myarray 还不存在。
  2. size 仍然 = 0,myarray 的长度为 0。
  3. 现在无论用户输入什么大小(可能是 5),但 myarray 的长度仍然为 0。

您需要交换第 2 行和第 3 行。

现在,补充一点——可变长度数组不是标准的 C++。无论如何,很多编译器都会处理它们,但使用它被认为是错误的。

大多数人会告诉你使用:

#include <vector>

...

std::vector<int> myArray;

但这更复杂。你也可以这样做:

int * myArray = new int[size];
...
// When done:
delete myArray;

如果您不打算使用 std::vector<>,这是正确的方法。


推荐阅读