Binary Search in C++

Here you will find out about Binary Search in C++.

Binary Search is a calculation used to search for a component in an arranged cluster. In this calculation the focused on the component is a contrasted and centre component.

On the off chance that the two components are equivalent, at that point position of the center component is returned and consequently focused on the component is found.

On the off chance that the two components are inconsistent, at that point whenever focused on the component is less or more than centre component we dispose of the lower or upper half and the search proceeds by finding new centre component.

Program for Binary Search in C++

#include<iostream>
 
using namespace std;
 
int main()
{
    int search(int [],int,int);
    int n,i,a[100],e,res;
    cout<<"How Many Elements:";
    cin>>n;
    cout<<"\nEnter Elements of Array in Ascending order\n";
    
    for(i=0;i<n;++i)
    {
        cin>>a[i];
    }
    
    cout<<"\nEnter element to search:";
    cin>>e;
    
    res=search(a,n,e);
    
    if(res!=-1)
        cout<<"\nElement found at position "<<res+1;
    else
        cout<<"\nElement is not found....!!!";
 
    return 0;
}
 
int search(int a[],int n,int e)
{
    int f,l,m;
    f=0;
    l=n-1;
    
    while(f<=l)
    {
        m=(f+l)/2;
        if(e==a[m])
            return(m);
        else
            if(e>a[m])
                f=m+1;
            else
                l=m-1;
    }
    
    return -1;
}

Output

How Many Elements:5

Enter Elements of Array in Ascending order
12 39 40 68 77

Enter element to search:40

Element found at position 3

Leave a Comment