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

What is 1d array?

461


What are the disadvantages array implementations of linked list?

471


Define balance factor of a node in avl tree?

595


Write a Program for Delete an element from a doubly linked list.

487


How many types of arrays are there?

512






What is complete binary tree in data structure?

511


What is arrays copyof?

461


Why set will not allow duplicates?

484


Which is the simplest file structure? (a) Sequential (b) Indexed (c) Random (a) Sequential

693


What do you mean by Logical Error

553


Which is the parent class of hashmap class?

574


What is linked list ?

525


Give a real time example of stack

544


Are duplicates allowed in list?

482


Is Arraylist faster than Array? Why?

528