【问题标题】:Binary search in array is not working properly [closed]数组中的二进制搜索无法正常工作[关闭]
【发布时间】:2021-10-15 15:48:06
【问题描述】:
// function for binary search in array
#include <iostream>
using namespace std;
int binSrch(int arr[], int n, int key)
{
    int s = 0, e = n; // s for starting and e for ending
    int mid = (s + e) / 2;
    while (s <= e)
    {
        if (arr[mid] == key)
            return mid;
        else if (arr[mid] > key)
            e = mid - 1;
        else
            s = mid + 1;
    }
    return -1;
}
int main()
{
    int n, key;
    cout << "enter no. of elements" << endl;
    cin >> n;
    int arr[n];
    cout << "enter array " << endl;
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
    }
    cout << "enter key" << endl;
    cin >> key;
    cout << binSrch(arr, n, key);
    return 0;
}

此数组中的二进制搜索代码不起作用。

对于某些数组,程序会卡住。我不知道做错了什么。

我以排序格式输入。

PS C:\Users\anmol\Desktop\c++projectwork> g++ .\binSearchArrFun.cpp
PS C:\Users\anmol\Desktop\c++projectwork> ./a
enter no. of elements
6
enter array 
2
3
4
5
6
7
enter key
8

它只是卡在这里而不是给-1

【问题讨论】:

  • 与您的问题无关,但您应该知道int arr[n]; 不是标准C++,您应该改用std::vector&lt;int&gt; arr(n);
  • 您需要在迭代中重新计算mid
  • 如果这不是学校作业,请尝试使用std::upper_boundstd::lower_bound
  • 不要在评论中解释 se 是什么,而是给它们起个名字来说明它们是什么。 startend 浮现在脑海中。

标签: c++ visual-studio binary-search


【解决方案1】:

假设您传递 n 作为数组的大小,您应该提供 e = n-1,因为数组是基于 0 索引的,这就是您可能得到错误答案的地方。 而且你还应该在每次迭代后计算mid,所以它应该在while loop内。

另外,您应该使用mid = s +(e-s)/2 来避免溢出。

【讨论】:

  • 谢谢,在 while 循环代码中放入 'mid' 后运行正常!
【解决方案2】:

我修改了你的代码。运行它,它应该清楚发生了什么。

#include <iostream>

using namespace std;

int binSrch(int arr[], int n, int key)
{
  int s = 0, e = n; // s for starting and e for ending
  int mid = (s + e) / 2;
  while (s <= e)
  {
    if (arr[mid] == key)
      return mid;
    else if (arr[mid] > key)
    {
      cout << "e = mid - 1;\n";
      e = mid - 1;
    }
    else
    {
      cout << "e = mid - 1;\n";
      s = mid + 1;
    }
  }
  return -1;
}

int main()
{
  int n = 4, key = 3;
  int arr[100] = { 1,3,4,10 };

  cout << binSrch(arr, n, key);
  return 0;
}

您可以使用这个修改后的main 进行测试。它会输出不起作用的测试用例。

int main()
{
  int n = 4;
  int arr[] = {1,3,4,10,11};

  // check for each element of arr if it is found
  // at the right position

  int index = 0;
  for (auto testval : arr)
  {
    if (! binSrch(arr, n, testval) == index)
      cout << "not OK for case" << testval << "\n";

    index++;
  }

  // check if 0 and 100 are not found

  if (binSrch(arr, n, 0) != -1)
    cout << "not OK for case" << 0 << "\n";

  if (binSrch(arr, n, 100) != -1)
    cout << "not OK for case" << 100 << "\n";  

  return 0;
}

【讨论】:

    猜你喜欢
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2020-10-25
    相关资源
    最近更新 更多