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 are basic algorithms?

631


What is time complexity of hashmap?

728


What is placement new in data structures?

672


Which is better hashmap or arraylist?

686


What do you mean by data and data structure?

688






Can we extend an array after initialization?

764


Write an algorithm for inserting and deleting an element from doubly linked list?

674


Does hashset allow duplicates?

748


How to find the duplicate in an array?

681


Describe full binary tree and complete binary tree.

667


What is default array size?

733


In what areas do data structures are applied?

704


Difference between arraylist and linkedlist?

757


What is dynamic array in excel?

624


Why quicksort is faster than merge sort?

670