Write a Binary Search program

Answer Posted / arnoldindia

#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 ?    51 Yes 23 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How do you sort in ascending order in arraylist?

495


Why quicksort is faster?

487


What are examples of data structures?

504


What does arrays tostring do?

474


Can you please explain the difference between string and an array?

513






How would you reverse the characters of an array?

528


How to excel in data structures and algorithms?

528


What is the difference between ienumerable and list?

470


Why is arraylist used?

481


What is the default capacity of hashmap?

409


Tell me why can't constant values be used to define an array's initial size

526


How many types of data structure are there?

454


What is Doubly link list?

547


What is the difference between linked list and array?

493


Tell me can the size of operator be used to tell the size of an array passed to a function?

512