#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAXSIZE 20
typedef struct
{
int r[MAXSIZE+1];
int length;
}SqList;
void swap(SqList * L,int i,int j)
{
int temp=L->r[i];
L->r[i]=L->r[j];
L->r[j]=temp;
}
void Merge(int SR[],int TR[],int i,int m,int n)
{
int j,k,l;
for(j=m+1,k=i;i<=m && j<=n;k++)
{
if(SR[i]<SR[j])
TR[k]=SR[i++];
else
TR[k]=SR[j++];
}
if(i<=m)
{
for(l=0;l<=m-i;l++)
TR[k+l]=SR[i+l];
}
if(j<=n)
{
for(l=0;l<=n-j;l++)
TR[k+l]=SR[j+l];
}
}
void MergePass(int SR[],int TR[],int s,int n)
{
int i=1;
int j;
while(i<=n-2*s+1)
{
Merge(SR,TR,i,i+s-1,i+2*s-1);
i=i+2*s;
}
if(i<n-s+1)
Merge(SR,TR,i,i+s-1,n);
else
for(j=i;j<=n;j++)
TR[j]=SR[j];
}
void MergeSort(SqList * L)
{
int * TR=(int *)malloc(L->length * sizeof(int));
int k=1;
while(k<L->length)
{
MergePass(L->r,TR,k,L->length);
k=2*k;
MergePass(TR,L->r,k,L->length);
k=2*k;
}
}
void print(SqList * L)
{
for(int i=1;i<=L->length;i++)
{
printf("%d ",L->r[i]);
}
printf("\n");
}
int main()
{
int n;
SqList L;
L.length=0;
printf("请输入元素个数:\n");
scanf("%d",&n);
srand(0);
for(int i=1;i<=n;i++)
{
L.r[i]=rand()%100+1;
L.length++;
}
printf("排序前的数组: ");
print(&L);
MergeSort(&L);
printf("排序后的数组: ");
print(&L);
}