My test cases are failing …why?
Arrays- Binary Search
Hey @dhanshree_p18
Did 3 changes
#include<iostream>
using namespace std;
int main() {
int n,key,s,e,mid,ans=-1;//initialized ans with -1 incase not found we have to print -1
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
s=0; e=n-1; //updated this line (indexes instead of elements)
cin>>key;
while(s<=e){
mid=(s+e)/2;
if(key==a[mid]){
ans=mid;
break;//added this otherwise run infinitely
}
else if(key<a[mid]){
e=mid-1;
}
else if(key>a[mid]){
s=mid+1;
}
}
cout<<ans<<endl;
return 0;
}
If this resolves your query then please mark it as resolved