I wrote a program for binary search but it is not working properly. I also wrote code to sort the array, which is working, but when I accept the element to be searched, the program stops working and returns undesired values. It is showing Process returned -1073741819 (0xC0000005)
each time I run the program. Here's my code
#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;
}
The bug seems to be in the following line:
mid = (last + mid)/2;
You want mid
to be assigned the value that is equidistant to both last
and beg
. Resolve this bug
in your code and it should work.