Binary Search Program in C++

In our earlier post we learned about Linear search.Today we shall learn about other type of searching technique…i.e is binary searching.This method is different form the earlier one.We shall go in detail about this.

If the data given by the user is stored in the array then the array will have three variable to named as first,last and middle.Each of the three variables are used in searching of the given array.

Method:1.Get the data from the user and store it in array.
2. Initialize the variables first to zero,last to the length of the array and middle to (first+last)/2.
3.Get the key value from the user to search in the array.
4.Now make a while loop with condition last>=first.
5.In the loop if element present in the middle of the given array is greater than key element then assign first to middle+1.
6.If the element in the middle of the given array is less than the key then assign last to middle-1.
7.If the element present in the middle of the array is equal to key then searching is completed.
8.End the loop.

Let us write the program following the above steps.

#include<iostream.h>
#include<conio.h>
class bsearch
{
  public:
  int data[10],n,key,first,last,middle;
  void getdata();
  void display();
};
void bsearch :: getdata()
{
  cout<<"\nEnter the length of the array:";
  cin>>n;
  for(int i=0;i<n;i++)
   {
     cout<<"\nEnter the element at position"<< (i+1)<<" of the array:";
     cin>>data[i];
   }
  cout<<"\nEnter the key to find the element in the array:";
  cin>>key;
}
void bsearch :: display()
{
  first=0;
  last=n-1;
  middle=(first+last)/2;
  while(last>=first)
  {
    middle=(first+last)/2;
    if(key>data[middle])
      first=middle+1;
    else if(key<data[middle])
      last=middle-1;
    else
    {
      cout<<"\nKey "<<key<<" found in the given array";
      break;
    }
  }
}
void main()
{
 clrscr();
 bsearch ob;
 ob.getdata();
 ob.display();
 getch();
}

OUTPUT:
bsearch
You can download the program:download
If you have any doubts please comment them.

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in C++ and tagged , , , , , , . Bookmark the permalink.

1 Response to Binary Search Program in C++

  1. Taniya says:

    Varry good job

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 )

Facebook photo

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

Connecting to %s