My photo
Bangalore, Karnataka, India
Extending one hand to help someone has more value rather than joining two hands for prayer

Archives

program for binary search of elements which are already sorted

Tuesday, September 1, 2009

#include<iostream.h>
#include<conio.h>
#include<process.h>
void main()
{ clrscr();
 int a[100],n,item,beg,mid,loc=-1,end;
 cout<<"enter the number of items: ";
 cin>>n;
 cout<<"enter the sorted element: "<<endl;
 for(int i=0;i<n;i++)
 cin>>a[i];
 cout<<"list of the item is"<<endl;
 for(i=0;i<n;i++)
 cout<<"element at location '"<<i<<"' = "<<a[i]<<endl;
 cout<<"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;
     cout<<"location of the element is: "<<loc;
     exit;
     }
     else if(item<a[mid])
     end=mid-1;
     else
     beg=mid+1;
  }
    if(loc==-1)
    cout<<"item could not found";
  getch();
  }

0 comments: