Sunday 6 October 2013

Binary Search program in C++

#include<iostream>
using namespace std;
#include<conio.h>
template<class T>
T binarysearch(T a[20],T n,T key)
{
                 int left,right,mid;
                 left=0;
                 right=n-1;
                 while(left<=right)
                 {
                                   mid=(left+right)/2;
                                   if(key==a[mid])
                                   return mid;
                                   else
                                   if(key<a[mid])
                                   right=mid-1;
                                   else
                                   left=mid+1;
                 }
                 return -1;
}
int main()
{
    int a[20],n,key,p,i;
    cout<<"\n enter number of elements:";
    cin>>n;
    cout<<"\n enter "<<n<<" values in ascending order :";
    for(i=0;i<n;i++)
    cin>>a[i];
    cout<<"\n enter the key value:";
    cin>>key;
    p=binarysearch(a,n,key);
    if(p!=-1)
    cout<<"\n the element is found at "<<p+1<<" position";
    else
    cout<<"\n search is unsucessful......";
    _getch();
    return 0;
}

No comments:

Post a Comment