二进制搜索程序返回不需要的值
Binary search program returning undesired values
我写了一个二进制搜索程序,但它不能正常工作。我还编写了对数组进行排序的代码,它正在工作,但是当我接受要搜索的元素时,程序停止工作并且 returns 不需要的值。每次我 运行 程序时它都显示 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
,它应该可以工作。
我写了一个二进制搜索程序,但它不能正常工作。我还编写了对数组进行排序的代码,它正在工作,但是当我接受要搜索的元素时,程序停止工作并且 returns 不需要的值。每次我 运行 程序时它都显示 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
,它应该可以工作。