Binary search Code

#include
using namespace std;
int binary_search(int a[],int n,int key)
{
int f=0;
int l=n-1;
while(l>f)
{
int mid=(f+l)/2;
if(a[mid]==key)
{
return mid;
}
else if(a[mid]>key)
{
l=mid-1;
}

    else if(a[mid]<key)
     {
        f=mid+1;
     }

}
if(f>l)
{
    cout<<"The given number is not present in the data";
}

}
int main()
{
int n;
int key;
cout<<“Enter the total number of elements in your data:”<<endl;
cin>>n;
int a[n];
cout<<“Enter the elements”<<endl;
for (int b=0;b<n;b++)
{
cin>>a[b];
}
cout<<“Enter the number you want to search”<<endl;
cin>>key;
int k=binary_search(a,n,key);
cout<<"The given number is present in the data at position= "<<k+1;
return 0;
}

This code shows error if the key is not present in the data

@juyal.sid return -1 and if not -1 then only print ans


dont forget to hit like and mark resolved if cleared :smiley:

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.