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

When would you use a tuple?

482


We know that Arrays are objects so why cannot we write strArray.length()?

1109


Reverse a linked list from the middle.

540


Why are b trees used?

513


How arraylist increase its size?

474






Define depth and height of a node?

518


Is quicksort a stable algorithm?

520


Which is better hashmap or hashtable?

475


Is hashtable fail fast?

452


How to do the intersection of two sorted arrays?

564


Can treemap have null values?

489


How to find 3rd element from end in a linked list in one pass?

466


Are the expressions arr and &arr same for an array of integers?

572


What is a property class?

510


Name some applications which use linked lists.

551