binary search Program in c++ for MCA

SOURCE CODE :

//programed by Paras Wadher
MCA
Nagpur university

//Program for searching any element using binary search.

#include
#include
class binsearch
{
public:
void binary_search(int,int,int *);
void sorting(int *,int);
void display(int *,int);
};
void binsearch::binary_search(int element,int n,int l[])
{
int flag=1;
int low,mid,high;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(element
{
high=mid-1;
}
else
{
if(element>l[mid])
{
low=mid+1;
}
else
{
if(element==l[mid])
{
cout<<“\n\n***Search is successful***”<<“\n”;
cout<<“\n\nElement “<<<” “<<“found at location = “<<(mid+1);
flag=0;
break;
}
}
}
}
if(flag)
{
cout<<“\n\n***Search is unsuccessful***”<<“\n”;
}
}
void binsearch::sorting(int list[],int num)
{
for(int j=0;j
{
for(int k=0;k
{
if(list[k]>list[k+1])
{
int temp=list[k];
list[k]=list[k+1];
list[k+1]=temp;
}
}
}
}
void binsearch::display(int list[],int num)
{
cout<<“\nEntered list is as follows in “;
cout<<“ASCENDING ORDER = “;
for(int i=0;i
{
cout<<” “<

}
}
void main()
{
binsearch search;
int num,key,list[200];
clrscr();
cout<<“\nInput the number of elements in the list=> “;
cin>>num;
cout<<“\n Number of elements in the list is “<<<“\n”;
cout<<“\nInput the elements of the list=”;
for(int i=0;i
{
cin>>list[i];
}
cout<<“\n Entered list is as follows==> “<<“\n\n”;
for(i=0;i
{
cout<<” “<

}
cout<<“\n\nElements to be searched : “;
cin>>key;
search.sorting(list,num);
search.display(list,num);
search.binary_search(key,num,list);
getch();
}

************************************************************
OUTPUT 1
************************************************************

Input the number of elements in the list=> 6

Number of elements in the list is 6

Input the elements of the list=4
6
7
8
9
0

Entered list is as follows==>

4 6 7 8 9 0

Elements to be searched : 0

Entered list is as follows in ASCENDING ORDER = 0 4 6 7 8 9

***Search is successful***

Element 0 found at location = 1

************************************************************************
OUTPUT 2
************************************************************************

Input the number of elements in the list=> 4

Number of elements in the list is 4

Input the elements of the list=6
4
2
0

Entered list is as follows==>

6 4 2 0

Elements to be searched : 3

Entered list is as follows in ASCENDING ORDER = 0 2 4 6

***Search is unsuccessful***

Leave a Reply

Your email address will not be published. Required fields are marked *