You are on page 1of 2

PROGRAM TO SEARCH AN ELEMENT USING BINARY SEARCH

#include<iostream.h>

#include<conio.h>

void main()

clrscr();

int a[100],n,i,item,mid,count=0;

cout<<"Enter the number of elements you want to enter\n";

cin>>n;

cout<<"Now enter the "<<n<<" number of elements\n";

for(i=0;i<n;i++)

cin>>a[i];

cout<<"Now enter the element the position of which u want to know\n";

cin>>item;

int beg=0;

int end=n;

while(beg<=end && count==0)

mid=(beg + end)/2;

if(item==a[mid])

count=mid+1;

cout<<"Num. is at pos="<<count;

break;

else if(item<a[mid])

end=mid-1;

}
else

beg=mid+1;

if(count==0)

cout<<"element dont exist";

getch();

You might also like