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

Which is more efficient merge sort vs quicksort?

632


Can you dynamically allocate arrays in expanded memory?

791


Are data structures important?

674


How would you reverse characters of an array without using indexing in the array.

675


Can you please explain the difference between array_name and &array_name?

748


Is treemap synchronized?

696


Define Data Structures?

747


Which sorting algorithm uses minimum number of swaps?

638


Which is the parent class of deque class?

696


Why would you use a linked list?

683


Explain the term tail recursion?

771


Define an algorithm.

736


Which is the parent class of enumset class?

741


What is sorting in data structure?

665


What do you mean by recursive definition?

692