Thursday, 20 June 2013

source code: Binary search using C++ [the most easiest way and user friendly as well]



#include<iostream>

 using namespace std;

int main()

{
   int  n, search, ary[100];

   cout<<"Enter number of elements: "; cin >>n;


   int beg= 0, end= n - 1, mid= (beg+end)/2;


   cout<<"Enter the elements: ";


   for (int x=0; x<n; x++)

      cin >>ary[x];

   cout<<"Enter the integer to find: "; cin>>search;



   while(beg <= end)

   {
      if (ary[mid] == search)
  {
 cout<<search <<" found at location:" <<mid+1 <<endl;
         break;
  }
           
      else if(ary[mid] < search)
      {
  beg= mid + 1;
       
      }
      else
         end= mid - 1;

      mid= (beg + end)/2;

   }
   if (beg > end)
      cout <<"no luck kid !";

   return 0;  

}

No comments:

Post a Comment