Earn without any Investment!

Tuesday, October 26, 2010

Binary Search

#include<iostream.h>
#include<conio.h>
class binary
{
 public:
  int a[50],n,x;
  void getdata();
  void getitem();
};
class search:public binary
{
 public:
 int high,j,low,temp;
  search()
  {
   temp=0,low=0;
  }
  void findata();
  void display();
};
void binary::getdata()
{
 cout<<"\n Enter the total no of value:";
 cin>>n;
 cout<<"\n Enter  "<<n<<" values one by one:";
 for(int i=0;i<n;i++)
 {
  cout<<"\n Position "<<i<<":";
  cin>>a[i];
 }
}
void binary::getitem()
{
 cout<<"\n Enter the value to be searched:";
 cin>>x;
}
void search::findata()
{
 high=n-1;
 do
 {
  j=(low+high)/2;
  if(a[j]==x)
  temp=1;
  else if(x<a[j])
  high=j-1;
  else
  low=j+1;
 }
 while(low<=high&&temp==0);
}
void search::display()
{
 if(temp==1)
 cout<<"\n The value is located the position:"<<j;
 else
 cout<<"\n The value is not found";
}
void main()
{
 clrscr();
 search s;
 s.getdata();
 s.getitem();
 s.findata();
 s.display();
 getch();
}

No comments:

Post a Comment