// function for binary search in array
#include <iostream>
using namespace std;
int binSrch(int arr[], int n, int key)
{
int s = 0, e = n; // s for starting and e for ending
int mid = (s + e) / 2;
while (s <= e)
{
if (arr[mid] == key)
return mid;
else if (arr[mid] > key)
e = mid - 1;
else
s = mid + 1;
}
return -1;
}
int main()
{
int n, key;
cout << "enter no. of elements" << endl;
cin >> n;
int arr[n];
cout << "enter array " << endl;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << "enter key" << endl;
cin >> key;
cout << binSrch(arr, n, key);
return 0;
}
This code for binary searching in array does not work.
For some array the program gets stuck. I don't know what did wrong.
I entered input in sorted format.
PS C:\Users\anmol\Desktop\c++projectwork> g++ .\binSearchArrFun.cpp
PS C:\Users\anmol\Desktop\c++projectwork> ./a
enter no. of elements
6
enter array
2
3
4
5
6
7
enter key
8
it just stuck here rather than giving -1
Assuming that you are passing n
as the size of the array, you should give e = n-1
since arrays are 0-indexed based, that is where you are probably getting the wrong answer.
And you also should calculate mid
after each iteration, so it should be inside the while loop
.
Also, you should do mid = s +(e-s)/2
to avoid overflow.