Binary Search in C++






#include <bits/stdc++.h>
using namespace std;
#define ll long long

ll mi,ma,mid,n;

ll binary_search(ll b[],ll key)
{
    ll m;
    mi=0;
    ma=n-1;

    while(ma>=mi)
    {
        mid=(mi+ma)/2;
        if(key<b[mid])
        {
            ma=mid-1;
        }
        else if(key>b[mid])
        {
            mi=mid+1;
        }
        else
        {
            return mid;
        }
    }

    return -1;
}

int main()
{
    ll a[100],i,j,k,f;
    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
    sort(a,a+n);
    cin>>k;
    f=binary_search(a,k);
    if(f>=0)
    {
        cout<<"Found="<<f+1<<endl;
    }
    else
    {
        cout<<"Not Found"<<endl;
    }

    return 0;
}

Share on Google Plus

About Ashadullah Shawon

I am Ashadullah Shawon. I am a Software Engineer. I studied Computer Science and Engineering (CSE) at RUET. I Like To Share Knowledge.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment