Binary Search- C++

 #include<iostream.h>  
 #include<conio.h>  
 class binary  
 {  
      private:  
           int a[20], n, x, i, high, low, mid, flag;  
      public:  
           void get( )  
           {  
                cout<<”\nEnter the limit : “;  
                cin>>n;  
                cout<<”\nEnter the elements : “;  
                for(i=0; i<n; i++)  
                     cin>>a[i];  
                cout<<”\nEnter the search element : “;  
                cin>>x;  
           }  
           void search( )  
           {  
                low=0;  
                high=n-1;  
                mid=(low+high)/2;  
                for(i=0; i<n; i++)  
                {  
                     if(x<a[mid])  
                     {  
                          high=mid-1;  
                          mid=(low+high)/2;  
                     }  
                     else if(x>a[mid]  
                     {  
                          low=mid+1;  
                          mid=(low+high)/2;  
                     }  
                     else if(x==a[mid])  
                     {  
                          cout<<”\nThe number is found”;  
                          break;  
                     }  
                     else  
                          cout<<”\nThe number is not found”;  
                }  
           }  
 };   
 void main( )  
 {  
      binary b;  
      clrscr( );  
      b.get( );  
      b.search( );  
      getch( );  
 }  

Share This!


No comments:

Post a Comment

Code Of The day - Suggest An Output For The Snippet

  #include<stdio.h>   
  int main()   
  {   
   float a=3.15529;   
   printf("%2.1f\n", a);   
   return 0;   
  }   
· A Code Archive - code1archive