WAP for binary search method
#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
int a[15],i,n,lb,ub,mid,item;
cout<<"\n Enter size of array :";
cin>>n;
cout<<"\n Enter sorted element for array :";
for(i=1;i<=n;i++)
cin>>a[i];
cout<<"\n Enter item which is to be search :";
cin>>item;
lb=1;
ub=n;
mid=int((lb+ub)/2);
while(a[mid]!=item && lb<=ub)
{
if(item<a[mid])
ub=mid-1;
else
lb=mid+1;
mid=int((lb+ub)/2);
}
if(a[mid]==item)
{
cout<<"\n search is successful ";
cout<<"\n location is= "<<mid;
}
else
cout<<"\n Search is unsuccessful ";
getch();
clrscr();
}
/* output
Enter size of array :5
Enter sorted element for array :11 22 33 44 55
Enter item which is to be search :44
search is successful
location is= 4 */
No comments:
Post a Comment