AIM:
To sort the given array of elements using binary search also to find the position of the item in the array
ALGORITHM:
Step 1: start the process
Step 2: Declare all the variables
Step 3: Get the size of the array
Step 4: Get all the values in an array variable
Step 5: use sort function to perform sort
Step 6: Search(), this function is used to search a particular element
Step 7: If the element found, display its memory location else
display not found
Step 8: After sorting print all the sorted elements
Step 9: Stop the process
Program:
#include<iostream.h>
class binary
{
int i,a[10],t,j,l,n;
public:
void get()
{
cout<<"\n\t********BINARY SEARCH*********\n";
cout<<"\t\n";
cout<<"\n ENTER THE SIZE OF ARRAY\n";
cin>>n;
cout<<"\n ENETER THE NUMBERS :\n";
for(i=0;i<n;i++)
cin>>a[i];
}
void sort()
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i]<a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
} } } }
void display()
{
cout<<"THE SORTED NUMBER ARE ::\n";
for(i=0;i<n;i++)
{
cout<<a[i]<<"\n";
}
}
void search()
{
int i,l=0,u,mid,item;
u=n-1;
cout<<"ENTER THE ITEM TO BE SEARCHED::\n";
cin>>item;
mid=(l+u)/2;
while((l<=u)&&(a[mid]!=item))
{
if(a[mid]>item)
u=mid-1;
else
l=mid+1;
mid=(l+u)/2;
}
if(a[mid]==item)
cout<<"the number"<< item <<"present in"<< mid+1 <<"location\n\n";
else
cout<<"the number is not present\n";
}
};
int main()
{
binary b;
b.get();
b.sort();
b.display();
b.search();
}
0 comments:
Post a Comment