【问题标题】:Correct my binarysearch index and out of range array更正我的二进制搜索索引和超出范围的数组
【发布时间】: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 的数组,然后问用户这个数组应该有多大,你认为现在的数组有多大?

标签: c++ arrays sorting helper


【解决方案1】:

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

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,这是正确的方法。

【讨论】:

  • 谢谢你,但我有一个问题,如果我输入数组大小 5 然后输入数组,例如 2 3 5 7 8 然后我要求它找到 7 并给出答案 3 因为索引是正确的?
  • @Keith 是的,这是正确的,因为数组是从零开始的,因此如果数组的大小为 5,则可以使用索引 0 - 4。索引 0 = 2,索引 1 = 3,索引 2 = 5,索引 3 = 7,索引 4 = 8。
猜你喜欢
  • 2016-03-29
  • 2019-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多