Write a program to sort elements of given array having ‘n’ number of elements,using Merge Sort.

#include
#include
main()
{
int a[50],c[100],n,i;
void merge(int *,int,int);
void mr(int*,int,int,int,int);
clrscr();
cout<>n;
cout<<"n Enter the elements of array n";
for(i=0;i<n;i++)
{
cout<<"n a["<<i<>a[i];
}
merge(a,0,n-1);

cout<<"nnn MERGED ARRAY IN ASCENDING ORDER IS n";
for(i=0;i<n;i++)
{
cout<<"n A["<<i<<"]="<<a[i];
}
getch();
return(0);
}
void mr(int *a,int lb,int le,int rb,int re)
{ cout<<"n FROM MERGING n";
cout<<"nn beg: "<<lb<<"mid: "<<le<<" mid+1: "<<rb<<" end: "<<re;
getch();
int s1,s2,s3,k,c[100];
s1=lb;
s2=rb;
s3=lb;
while((s1<=le)&&(s2<=re))
{
if(a[s1]le)
{
while(s2<=re)
{
c[s3]=a[s2];
s2++;
s3++;
}
}
else
{
while(s1<=le)
{
c[s3]=a[s1];
s3++;
s1++;
}
}
for(k=lb;k<=re;k++)
{
a[k]=c[k];
}
}
void merge(int *a,int beg,int end)
{
int mid;
cout<<"n From Merge Sort Function :n";
if(beg<end)
{
mid=(beg+end)/2;
cout<<"n beg:"<<beg<<"mid:"<<mid<<"end:"<<end;
getch();
merge(a,beg,mid);
merge(a,mid+1,end);
mr(a,beg,mid,mid+1,end);
}
}

Leave a Reply

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