//To search
an element in array using binary search
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<"Enter the no.of elements in array ";
cin>>n;
cout<<"\nEnter the elements \n";
for(i=1;i<=n;i++)
{
cin>>a[i];
}
for(i=1;i<=n-1;i++)
{
for(j=1;j<=n-i;j++)
{
if (a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
cout<<"\nSorted array: ";
for(i=1;i<=n;i++)
{
cout<<a[i]<<" ";
}
cout<<"\nEnter the element to be searched
\n";
cin>>item;
int beg,end,mid,loc=-1;
beg=1;
end=n;
mid=int(beg+end)/2;
while((beg<=end) && (loc==-1))
{
if (a[mid]==item)
{
loc=mid;
}
else if
(item<a[mid])
{
end=mid-1;
}
else
{
beg=mid+1;
}
mid=int(beg+end)/2;
}
if (loc==-1)
cout<<"search unsuccessfull";
else
cout<<"search successfull"<<"\t
location = "<<loc;
getch();
}
No comments :
Post a Comment