BINARY SEARCH in c++




Binary search

Binary search is useful for large data. It is faster than linear search but complex.Here an example of linear search...





#include <iostream>
using namespace std;
const int size=6;
void main ()
{

          int a[size]={4,5,6,7,7,8};
         
         
          int n;
          cout<<"enter the no which you want to search:";
          cin>>n;
          bool found=false;
          int low=0,high=size-1;
          int mid=(low+high+1)/2;
          while(low<=high&&!found){
                   if(a[mid]==n)
                             found=true;
                   else if(a[mid]>n)
                             high=mid-1;
                   else
                             low=mid+1;
                   mid=(low+high+1)/2;

}
          if(found==true)
                  
                             cout<<"NO:"<<n<< "is found at location:"<<mid<<endl;
                   else
                             cout<<"NOT found";
}