我编写了一个用于二进制搜索的程序,但是无法正常工作。我还编写了对数组进行排序的代码,该数组正在工作,但是当我接受要搜索的元素时,程序将停止工作并返回不希望的值。每次我运行该程序时都显示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;
}
该错误似乎在以下行中:
mid = (last + mid)/2;
您想要为mid
分配与last
和beg
等距的值。在您的代码中解析此bug
,它应该可以工作。