#include
#include
#define SIZE 10
class Array
{
int a[SIZE];
int n;
public:
void read();
void merge_sort(int,int);
void merge(int,int,int);
void display();
};
void Array::read()
{
cout<<"Enter the size of the array:";
cin>>n;
cout<<"Enter the "<
cin>>a[i];
merge_sort(1,n);
}
void Array::merge_sort(int low,int high)
{
int mid;
if(low
mid=(low+high)/2;
merge_sort(low,mid);
merge_sort(mid+1,high);
merge(low,mid,high);
}
}
//merges the subarrays
void Array::merge(int low,int mid,int high)
{
int i,j,k;
int c[SIZE];
i=low;
j=mid+1;
k=low;
while((i<=mid)&&(j<=high))
{
if(a[i]<=a[j])
{
c[k]=a[i];
k++;
i++;
}
else
{
c[k]=a[j];
k++;
j++;
}
}
if(i>mid)
{
for(int m=j;m<=high;m++,k++)
c[k]=a[m];
}
else
{
for(int m=i;m<=mid;m++,k++)
c[k]=a[m];
}
for(i=low;i<=high;i++)
a[i]= c[i];
}
void Array::display()
{
for(int i=1;i<=n;i++)
cout< }
void main()
{
Array a;
clrscr();
a.read();
cout<<"\nAfter Sorting the array is\n";
a.display();
getch();
}
OUTPUT
Enter the size of the array:6
Enter the 6 elements:
6
5
4
3
2
1
After Sorting the array is
1 2 3 4 5 6
No comments:
Post a Comment