You are on page 1of 2

BINARY SEARCH

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int Bsearch(int[],int,int);
int A[100],N,x,pos,i;
cout<<"Enter size of an array:";
cin>>N;
cout<<"\n Enter elements in an array:";
for(i=0;i<N;i++)
{
cin>>A[i];
}
cout<<"\n Enter elements you want to search:";
cin>>x;
pos=Bsearch(A,N,x);
if(pos==-1)
cout<<"\n Element not found";
else
cout<<"\n Element found at location number="<<pos;
getch();
}

int Bsearch(int A[],int N,int x)


{
int beg,mid,last;
beg=0;
last=N-1;
while(beg<=last)
{
mid=(beg+last)/2;

BINARY SEARCH
if(A[mid]==x)
return mid;
else
if(x>A[mid])
beg=mid+1;
else
last=mid-1;
}
return -1;
}

You might also like