Pages

May 8, 2012

wap in c++ for binary search.



#include<iostream.h>
#include<conio.h>


void main()
{
clrscr();
int a[10],n,beg,end,mid,item;
cout<<"\nNo of element in array\t";
cin>>n;
cout<<"enter the element\n";
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"\nenter item to be searched\t";
cin>>item;
beg=0;end=n;
mid=(beg+end)/2;
while(beg<=end&&a[mid]!=item)
{
if(item<a[mid])
{
end=mid-1;
}
else
{
beg=mid+1;
}
mid=(beg+end)/2;
}
if(a[mid]==item)
{
cout<<"\nitem found at loc "<<mid+1;
}
else
{
cout<<"\nitem not found";
}
getch();
}

No comments:

Post a Comment