首页 > 解决方案 > 二进制搜索程序返回不需要的值

问题描述

我为二进制搜索编写了一个程序,但它无法正常工作。我还编写了对数组进行排序的代码,它正在工作,但是当我接受要搜索的元素时,程序停止工作并返回不需要的值。Process returned -1073741819 (0xC0000005)每次运行程序时都会显示。这是我的代码

#include <iostream>
using namespace std;

int main() {
  int arr[10], n, i, j, temp;

  cout << "Enter number of elements: ";
  cin >> n;

  for (i = 0; i < n; i++) {
    cout << "Enter element " << i + 1 << ": ";
    cin >> arr[i];
  }

  cout << "\nThe sorted array is: \n";

  for (i = 0; i < n; i++) {
    for (j = 0; j < n - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }

  for (i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }

  int last, beg, mid, se, flag = 0;

  cout << "\n.\nEnter the element to be searched: ";
  cin >> se;

  last = n - 1;
  beg = 0;

  while (beg <= last) {
    mid = (last + mid) / 2;

    if (se > arr[mid])
      beg = mid + 1;

    else if (se < arr[mid])
      last = mid - 1;

    else {
      cout << se << " found at position " << mid + 1;
      flag = 1;
      break;
    }
  }

  if (flag == 0) cout << "No such thing exists...";

  return 0;
}

标签: c++codeblocksbinary-search

解决方案


该错误似乎在以下行中:

mid = (last + mid)/2; 

您希望分配与和mid等距的值。在您的代码中解决这个问题,它应该可以工作。lastbegbug


推荐阅读