Binary Search

<br />#include<iostream>
using namespace std;

main()
{
int n,i,j,*a,x,temp;
int beg,mid,last,y,flag;
cout<<"Enter total no. of elements:";
cin>>n;
a=new int[n];
cout<<"nEnter "<<n<<" elements:";
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"nThe elements are:";
for(i=0;i<n;i++)
{
cout<<"t"<<a[i];
}
cout<<"nnHow do you want to sort:";
cout<<"n1.in ascending order";
cout<<"n2.in descending order";
cout<<"nnEnter your option:";
cin>>x;
if(x==1)
{
flag=1;
for(i=1;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
cout<<"nThe sorted elements in ascending order are:";
for(i=0;i<n;i++)
{
cout<<"t"<<a[i];
}
}
else
{
for(i=1;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]<a[j+1])
{
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
cout<<"nThe sorted elements in descending order are:";
for(i=0;i<n;i++)
{
cout<<"t"<<a[i];
}
}
cout<<"nEnter the elements you want to search:";
cin>>y;
beg=0;
last=n-1;
if(flag==1)
{
while(beg<=last)
{
mid=(beg+last)/2;
if(y==a[mid])
{
cout<<y<<" elements is found at location "<<mid+1;
break;
}
else if(y>a[mid])
{
beg=mid+1;
}
else
{
last=mid-1;
}
}
if(beg>last)
{
cout<<"nNot found! "<<y<<" is not present in the list";
}
}
else
{
while(beg<=last)
{
mid=(beg+last)/2;
if(y==a[mid])
{
cout<<y<<" elements is found at location "<<mid+1;
break;
}
else if(y>a[mid])
{
last=mid-1;
}
else
{
beg=mid+1;
}
if(beg>last)
{
cout<<"nNot found! "<<y<<" is not present in the list";
}
}
}
cout<<"nn@Myprogworld......!!!nn";
}

Output :-
Binary Search

Leave a comment