Question { Microsoft, 25821 }
Write a Binary Search program
Answer
Answer
# 1 #include
#include
#include
int binarysearch(int list[], int end, int target, int &locn)
{
int first=0, mid, last=end;
while(first<=last)
{
mid=(first+last)/2;
if(target>list[mid])
first=mid+1;
else if(target
last=mid-1;
else
break;
}
locn=mid+1;
return(target==list[mid]);
}
void main()
{
int a[10],i,s=0,n,loc,flag=0;
clrscr();
cout<<"\n Enter the no. of element to store:\n";
cin>>n;
cout<<"Enter the Elements:\n";
for(i=0;i
cin>>a[i];
cout<<"\n The Elements are:\n";
for(i=0;i
cout<
cout<<"\n Enter the Element to search:\n";
cin>>s;
if(binarysearch(a,n,s,&loc))
cout<<"\nThe element "<
at location
"<
else
cout<<"\nThe element "<
in the List"<
}