C++ IMPLEMENTATION OF BINARY SEARCH

Binary Search C Implementation      Binary Search C++ Implementation

/* binary search */

#include<iostream.h>
#include<conio.h>
int bsearch(int a[],int n,int n1);
void main()
{
int a[20],i,n,item,pos;
clrscr();
cout<<“enter the size of the array “;
cin>>n;
cout<<“enter elements in sorted order”<<endl;
for(i=0;i<n;i++)
{
cout<<“enter the element ” ;
cin>>a[i];
}

cout<<“enter the element to search “;
cin>>item;
pos=bsearch(a,n,item);
if(pos==-1)
cout<<“Element is not present”<<endl;
else
cout<<“Element found at loation “<<pos+1<<endl;
getch();
}
int bsearch(int a[],int n,int item)
{
int first,last,mid,pos;
first=0;
last=n-1;
/* to search the array */
while(first<=last)
{
mid=(first+last)/2;
if (item==a[mid])
return(mid);
else
if (item>a[mid])
first=mid+1;
else
last=mid-1;
}
return(-1);
}

Binary Search C Implementation      Binary Search C++ Implementation