Pages

Monday, February 21, 2011

BINARY SEARCH

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a[50],x,n,beg,end,mid,flag;
cout<<"////////////////BINARY SEARCH//////////////////";
cout<<"\n enter the size of array";
cin>>n;
cout<<" enter the sorted array";
for(int i=1;i<=n;i++)
cin>>a[i];
cout<<" enter the element to search";
cin>>x;
beg=1;
end=n;
mid=(beg+end)/2;
while(beg<=end)
{
mid=(beg+end)/2;
if(a[mid]==x)
{
flag=1;break;

}
else if(x<a[mid])
{
end=mid-1;
}
else
{
beg=mid+1;
}
}
if(flag==1)
cout<<"element found at position "<<mid;
else
cout<<" element is not in above array";
getch();
}

No comments:

Post a Comment