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

Can arraylist shrink?

496


Can you change size of array once created?

466


How can a binary tree be represented using the rotation?

542


What is the difference between for and foreach loop?

473


What is binary tree example?

577






What is a hashmap in c?

497


Define primary data structures?

591


Run time memory allocation is known as in data structure?

543


Differentiate between hashmap and treemap.

517


Given an array of integers, devise a program to replace every element with the next greatest element on the right side in the array. Also, replace the last element with 5 as there no element on the right side of it.

573


How does hashset maintain order?

529


Design a datastructure to represent the movement of a knight on a chess board

566


What is data structure explain in detail?

522


State the merit of linked representation of binary trees?

538


What is collection process?

524