Write a Binary Search program

Answer Posted / rahul awasthi

Answer
# 1 #include<conio.h>
#include<iostream.h>
#include<process.h>

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<list[mid])
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<n;i++)
cin>>a[i];

cout<<"\n The Elements are:\n";
for(i=0;i<n;i++)
cout<<a[i]<<"\t";

cout<<"\n Enter the Element to search:\n";
cin>>s;

if(binarysearch(a,n,s,&loc))
cout<<"\nThe element "<<s<< " is available
at location
"<<loc<<endl;
else
cout<<"\nThe element "<<s<< " is not found
in the List"<<endl;


}

Is This Answer Correct ?    21 Yes 20 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are skew trees? For a tree with 4 nodes draw all possible binary? Generalize for n nodes how many binary trees can be drawn?

704


What is stack push?

547


What is the use of data structure?

600


Which is better hashmap or treemap?

594


Why is data structure needed?

605






What is frozenset?

552


Does treemap allow null keys?

595


Explain the common uses of threaded binary tree.

677


What is the most used data structure?

541


How does a hashmap work?

595


Describe queue operation.

589


What is the meaning of arraylist?

572


Which is better arraylist or linkedlist?

540


Is list an array?

514


Why is bubble sort stable?

563