Earn without any Investment!

Monday, November 8, 2010

Binary Search using C++

#include<iostream.h>
#include<conio.h>
void main()
{
   int arr[20];
   int n;
   int i;

   while(1)
   {
      cout<<"\nEnter the number of elements in the array:";
      cin>>n;
      if((n>1)&&(n<=20))
               break;
      else
               cout<<"\nArray should have minimum 1 and maximum 20 elements\n\n";

    }

    cout<<"Enter elements in ascending order:\n";
   
    for(i=0;i<n;i++)
    {
         cout<<"<"<< (i+1) <<">";
         cin>>arr[i];
    }

    char ch;
    do
    {
       int item,ctr;
       cout<<"\nEnter the element to be searched:";
       cin>>item;
       int lowerbound=0;
       int upperbound=n-1;
       int mid=(lowerbound+upperbound)/2;
       while((item!=arr[mid])&&(lowerbound<=upperbound))
    {
         if(item>arr[mid])
             lowerbound=mid+1;
         else
             upperbound=mid-1;
          mid=(lowerbound+upperbound)/2;
          ctr++;
         }
         if(item==arr[mid])
               cout<<"\n"<<item<<" found in the position "<<(mid+1)<<endl;
         else
               cout<<"\n"<<item<<" not found in the array"<<endl;
          cout<<"\nNumber of comparisions:"<<ctr;
          cout<<"\n\nContinue search (y/n):";
          cin>>ch;
       }while((ch=='y')||(ch=='Y'));
}

No comments:

Post a Comment