$$$ MERGE SORT $$$
PROGRAM:
#include<iostream>
int
a[20],temp[20],i,n;
class
mergesorting
{
public:
void getdata()
{
cout<<"\nEnter the array
limit:";
cin>>n;
cout<<"Enter array
elements:";
for(i=0;i<n;i++)
{
cin>>a[i];
}
}
void mergesort(int
a[],int temp[],int n)
{
msort(a,temp,0,n-1);
}
void msort(int
a[],int temp[],int left,int right)
{
int center;
if(left<right)
{
center=(left+right)/2;
msort(a,temp,left,center);
msort(a,temp,center+1,right);
merge(a,temp,left,center+1,right);
}
}
void merge(int
a[],int temp[],int left,int center,int right)
{
int i,left_end,num_elements,tmp_pos;
left_end=center-1;
tmp_pos=left;
num_elements=right-left+1;
while((left<=left_end)&&(center<=right))
{
if(a[left]<=a[center])
{
temp[tmp_pos]=a[left];
tmp_pos++;
left++;
}
else
{
temp[tmp_pos]=a[center];
tmp_pos++;
center++;
}
}
while(left<=left_end)
{
temp[tmp_pos]=a[left];
left++;
tmp_pos++;
}
while(center<=right)
{
temp[tmp_pos]=a[center];
center++;
tmp_pos++;
}
for(i=0;i<=num_elements;i++)
{
a[right]=temp[right];
right--;
}
}
void putdata()
{
cout<<"The Sorted elements
are:\t";
for(i=0;i<n;i++)
{
cout<<a[i]<<"\t";
}
}
};
void main()
{
mergesorting ms;
cout<<"$$$ MERGE SORT
$$$";
ms.getdata();
ms.mergesort(a,temp,n);
ms.putdata();
}
OUTPUT:
$$$ MERGE SORT $$$
Enter the array limit: 8
Enter array elements: 40 20 70 14 60 61 97 30
The Sorted elements are: 14 20 30 40 60 61 70 97
Enter the array limit: 8
Enter array elements: 40 20 70 14 60 61 97 30
The Sorted elements are: 14 20 30 40 60 61 70 97
No comments:
Post a Comment