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 many pointers are necessary to implement a simple linked list?

783


Which process places data at the back of the queue?

765


What is a data structure? What are the types of data structures? Briefly explain them

628


Why do we need algorithm?

563


Mention the steps to insert data at the starting of a singly linked list?

660






Is a hashset ordered?

574


Explain merge sort algorithms.

658


How do you implement a stack?

555


List the area of applications where stack data structure can be used?

600


What is a sorting algorithm in data structure?

573


What is time complexity of arrays sort?

596


Which sort is stable?

625


How to find middle element of linked list in one pass?

614


Can arraylist be resized?

665


Tell me is it better to use a pointer to navigate an array of values, or is it better to use a subscripted array name?

600