This is a simple binary search program, but for some reason, the program just doesn't move on after asking for the value of the key from the user. At first, I thought it is an issue with my compiler, but it still happens wherever I paste the code, and I don't know why.
#include <iostream>
using namespace std;
int binary(int arr[], int n, int k){
int s = 0;
int e = n;
int mid = (s+e)/2;
while(s<=e){
if(k==arr[mid]){
return mid;
}
else if(k>arr[mid]){
s = mid+1;
}
else if(k<arr[mid]){
e = mid-1;
}
}
return -1;
}
int main(){
int i, n, key;
cin>>n;
int a[n];
for(i=0;i<n;i++){
cin>>a[i];
}
cout<<"Enter key:"<<endl;
cin>>key;
cout<< binary(a, n, key);
}
Instead of moving on after k
, the code just does nothing.