Binary search problem

why it can’t pass the last test case
#include
#include
using namespace std;
int binarySearch(int arr[], int n, int key){
int s = 0;
int e = n-1;
int ans =-1;
while(s<=e){
int mid = (s+e)/2;
if(arr[mid]==key)
return mid;
else if(mid>key)
s= mid+1;
else
e=mid-1;
}
return ans;
}
int main() {
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int key;
cin>>key;
sort(arr,arr+n);
cout<<binarySearch(arr,n,key);
return 0;
}

In the “else if” conditional statement,
You are checking if mid>key and if it satisfies,
You are setting s=mid+1;

Corrections:

  1. arr[mid]>key
  2. Rather increasing s to mid+1 you should decrease e to mid-1 (because if key is smaller than arr[mid], then it must be lying between s and mid-1)

Hope, this would help.
If you still have doubts, feel free to aks.