Binary Search


/********************************************************

-> This C++ program is to implement binary search algorithm

-> This program works in Microsoft vc++ environment

*********************************************************/

#include<iostream.h>

class searching
{
private:
 double *array;
 int n;
public:
 void input();
 void bubblesort();
 void binarysearch();
};

void searching::input()
{
 cout<<“****************************************************\n”
  <<“This program is to implement binary search algorithm\n”
  <<“****************************************************\n”;
 cout<<“Enter how many numbers you are going to enter::”;
 cin>>n;
 array=new double[n+1];
 cout<<“Now enter your elements ::\n”;
 for(int i=1;i<=n;i++)
  cin>>array[i];
}

void searching::bubblesort()
{
    for(int i=1;i<=n-1;i++)
 {
    for(int j=1;j<=n-i;j++)
       if(array[j]>=array[j+1])
          array[j]+=array[j+1],
    array[j+1]=array[j]-array[j+1],
    array[j]=array[j]-array[j+1];
 }
}

void searching::binarysearch()
{
 cout<<“Enter the element to be searched ::”;
 double x;
 cin>>x;

 int low=1,high=n;

 while(low<=high)
 {
  int middle=(low+high)/2;

  if(x<array[middle])
   high=middle-1;
  else if(x>array[middle])
   low=middle+1;
  else
  {
   cout<<“found \n”;
   return;
  }
 }
 cout<<“search unsuccessful\n”;
}

int main()
{
 searching obj;
 obj.input();
 obj.bubblesort();
 obj.binarysearch();
 return 0;
}
/*****************************************************************

SAMPLE OUTPUT ::

****************************************************
This program is to implement binary search algorithm
****************************************************
Enter how many numbers you are going to enter::5
Now enter your elements ::
1.3
1.2
1.6
1.5
1.4
Enter the element to be searched ::1.4
found
Press any key to continue

********************************************************************/

One thought on “Binary Search”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s