Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
//  Program to implement Binary search


#include<iostream.h>
#include<iomanip.h>
class binarysearch
{

private:
     int *x;
     int items;
public:
     binarysearch(int);
     ~binarysearch();
     void input(int []);
     int search(int);
};

binarysearch::binarysearch(int n)
{
     items=n;
     x=new int[items];
}

binarysearch::~binarysearch()
{
     delete [] x;
}


void binarysearch::input(int a[])
{
     for(int i=0;i<items;i++)
     x[i]=a[i];
}


int binarysearch::search(int number)
{

     int low=0;
     int high=items-1;
     int mid;
     while(low<=high)
     {
     mid=(low+high)/2;
     if(x[mid]<number)
     low=mid+1;
     else if(x[mid]>number)
     high=mid-1;
     else if(x[mid]==number)
     return mid+1;
     else return 0;
     }
}



int main()
{
     int a[100],n,temp;
     cout<<" Enter how many elements \n";
     cin>>n;
     cout<<" Enter "<<n<<"elements in increasing order \n";
     for(int i=0;i<n;i++)
     cin>>a[i];
     cout<<"\n Enter search number :";
     cin>>temp;
     binarysearch obj(n);
     obj.input(a);
     int position=obj.search(temp);
     if(position!=0)
     cout<<"\n Search number is present and its position:"<<position;
     else
     cout<<"\n search number is not present";
     return 0;
}



Test data

Enter how many elements
8
Enter 8 elements in increasing order
12  13  16  17  20  29  56  78

Enter search number : 17

Output
Search number is present and its position :4