#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();
}
By Er Gurpreet Singh,
Senior Software Engineer,
Sopra Steria India
Sunday, 2 August 2015
Binary Search Program
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment