Saturday 1 August 2015

Binary Search Program



#include<iostream.h>
#include<conio.h>
void main()
{ 
 clrscr();
int n,*a,item,loc=-1;
cout<<"\nenter the no. of elements :";
cin>>n;
a=new int[n];  //dynamically initialize array
cout<<"\nenter the elements:\n";
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"\nenter the element you want to search: ";
cin>>item;
int mid,end=n,beg=0;
while(beg<=end&&loc==-1)
{
 mid=(beg+end)/2;
 if(a[mid]==item)
  loc=mid; 
 else if(a[mid]<item)
  beg=mid+1;
 else
  end=mid-1;
}
if(loc!=-1)
      cout<<"\nlocation of "<<item<<" is:"<<loc+1;
else
      cout<<"\n"<<item<<" not found!!!";
getch();
}

No comments:

Post a Comment