BINARY SEARCH
Write a C++ program to accept a single dimensional
array and search for an element by Binary search.
#include<iostream.h>
#include<conio.h>
int bsearch(int[],int,int);
void main()
{
clrscr();
int a[50],item,n,index;
cout<<"Enter array size ";
cin>>n;
cout<<"\nEnter array elements
:";
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"\nEnter an element to be
searched for";
cin>>item;
index = bsearch(a,n,item);
if(index==-1)
cout<<"Given
element not found";
else
cout<<"\nElement
found at index :"<<index<< ", position :"<<index+1<<endl;
getch();
}
int bsearch(int a[],int size,
int item)
{
for(int
i=0;i<size;i++)
{
int beg,last,mid;
beg=0,last=size-1;
while(beg<=last)
{
mid=(beg+last)/2;
if(item==a[mid])
return mid;
else if(item<a[mid])
beg=mid+1;
else
last=mid-1;
}
return
i;
}
return -1;
}
No comments:
Post a Comment