Friday, 29 June 2012

Binary Search Using c++


#include<iostream.h>
#include<conio.h>
  void main()
  {
   int a[15],n,i,loc=-1,item,chk=0,beg,end,mid;
   clrscr();
    cout<<endl<<"enter the no of elements :";
    cin>>n;
     cout<<endl<<"enter the elements :";
      for(i=0;i<n;i++)
      {
cout<<endl<<"a["<<i<<"] = ";
cin>>a[i];
      }
    cout<<endl<<"enter the item to be searched :";
    cin>>item;
    beg=0;
    end=n-1;
     while(beg<=end&&loc==-1)
     {
       mid=(beg+end)/2;
       if(item==a[mid])
       {
 loc=mid;
 chk=1;
 break;
       }
       else if(item<a[mid])
       {
end=mid-1;
       }
       else
       {
beg=mid+1;
       }
     }
      if(chk==1)
      {
       cout<<endl<<"item is present at "<<loc<<" loc";
      }
      else
      {
cout<<endl<<"item is not present in the list :";
      }
   getch();
  }

No comments:

Post a Comment