# include <stdio.h>
main()
{
int x[100],y[100],z[100],n,i,l;
clrscr();
printf("\t\t\t\t MERGE SORT\n");
printf("\n\nEnter the no. of elements:\n");
scanf("%d",&n);
printf("\nEnter the elements.\n");
for(i=1;i<=n;i++)
scanf("%d",&x[i]);
printf("\nIterations:\n");
l=1;
while(l<n)
{
mpass(x,y,n,l);
l=2*l;
mpass(y,x,n,l);
l=2*l;
}
for(i=1;i<=n;i++)
printf("%d ",x[i]);
printf("\n");
getch();
clrscr();
printf("\nThe sorted elements are...\n");
for(i=1;i<=n;i++)
printf("%d ",x[i]);
getch();
}
mpass(int x[],int y[],int n,int l)
{
int i,q,z;
i=1;
while(i<=n-(2*l)+1)
{
merge(x,i,i+l-1,i+(2*l)-1,y);
i=i+(2*l);
}
if(i+l-1<n)
merge(x,i,i+l-1,n,y);
else
for(q=i;q<=n;q++)
y[q]=x[q];
for(z=1;z<=n;z++)
printf("%d ",x[z]);
printf("\n");
}
merge(int x[],int l,int m,int n,int z[])
{
int i,j,k,r;
i=k=l;j=m+1;
while((i<=m)&&(j<=n))
{
if(x[i]<=x[j])
{
z[k]=x[i];
i++;
}
else
{
z[k]=x[j];
j++;
}
k++;
}
if(i>m)
for(r=j;k<=n;k++)
{
z[k]=x[r];
k++;
}
else
for(r=i;r<=m;r++)
{
z[k]=x[r];
k++;
}
return;
}
No comments:
Post a Comment