Why this code is not working?

#include
using namespace std;
int binarysearch(int a[],int n,int key)
{
//n denotes no. of element in an array
int s=0;
int e=n-1;
int mid=(s+e)/2;

while(s<=e)
{
    //Means we can compute mid
    if(a[mid]==key)
    {
        return mid;
    }
    //Key in Left Half
    else if(a[mid]>key)
    {
        e=mid-1;
    }
    else{
        s=mid+1;
    }
}
return -1;

}
int main() {
// cout<<“Hello World!”;
//Divide and Conquer Starting
int a[]={1,3,5,10,12,15,17};
int n=sizeof(a)/sizeof(int);
int key;
cin>>key;
int searchi=binarysearch(a,n,key);
if(searchi==-1)
{
cout<<“Element not found.”;
}
else{
cout<<searchi;
}

}

Hi @aryangrover you are not updating the value of mid anywhere, so place the int mid = (s+e)/2 statement inside the while loop, before the first if condition.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.