吴越子坤——递归归并排序

#include

#define MAXSIZE 10000  
typedef struct {
	int r[MAXSIZE+1];
	int length;
} SqList;
#define N 9

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];		/* 将剩余的SR[i..m]复制到TR */
	}
	if(j<=n)
	{
		for(l=0;l<=n-j;l++)
			TR[k+l]=SR[j+l];		/* 将剩余的SR[j..n]复制到TR */
	}
}

void MSort(int SR[],int TR1[],int s,int t){
	int m;
	int TR2[MAXSIZE+1];
	if(s==t) TR1[s]=SR[s];
	else {
		m = (s+t)/2;
		MSort(SR,TR2,s,m);
		MSort(SR,TR2,m+1,t);
		Merge(TR2,TR1,s,m,t);
	}
}
void MergeSort(SqList *L){
	MSort(L->r,L->r,1,L->length);
}
void print(SqList L)
{
	int i;
	for(i=1;i<L.length;i++)
		printf("%d,",L.r[i]);
	printf("%d",L.r[i]);
	printf("\n");
}

int main()
{
   int i;
   
   /* int d[N]={9,1,5,8,3,7,4,6,2}; */
   int d[N]={50,10,90,30,70,40,80,60,20};
   /* int d[N]={9,8,7,6,5,4,3,2,1}; */

   SqList l0,l1,l2,l3,l4,l5,l6,l7,l8,l9,l10;
   
   for(i=0;i<N;i++)
     l0.r[i+1]=d[i];
   l0.length=N;
   l1=l2=l3=l4=l5=l6=l7=l8=l9=l10=l0;
   printf("排序前:\n");
   print(l0);
  
   printf("归并排序(递归):\n");
   MergeSort(&l7);
   print(l7);

	return 0;
}

你可能感兴趣的:(c语言与算法,算法)