c++ - 二进制搜索程序返回不需要的值
问题描述
我为二进制搜索编写了一个程序,但它无法正常工作。我还编写了对数组进行排序的代码,它正在工作,但是当我接受要搜索的元素时,程序停止工作并返回不需要的值。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
推荐阅读
- python - Python 3.6.4 脚本在调试模式下工作,但在终端上运行时返回错误
- linux - select() 是阻塞调用还是非阻塞调用
- r - R:绘制混合效应模型绘制结果
- php - 带有上一期和下一期链接的 WooCommerce 产品类别页面
- python - Python为udp打开多个cmd提示
- sql - 没有重复条件的表并集
- python - 如何使用以下逻辑在python中编写罗马数字到整数转换的代码
- linux - for循环中的slurm作业名称
- c# - 从现有的 Json 流中删除 $ type 和 Id 属性?
- javascript - 使用隐藏和显示自动更新jquery中的多个下拉菜单