归并排序(递归与分治)

#include <stdio.h>
#include <stdlib.h>
void mer (int a[],int l,int m,int r )    //合并函数
	{
		int i,j,k;
          int n1=m-l+1;
		  int n2=r-m;
		  int *f,*b;
		  f=(int *) malloc (n1*sizeof (int));
		  b=(int *) malloc (n2*sizeof (int));
		  for (i=0;i<n1;i++)
			  f[i]=a[l+i];
		  for (i=0;i<n2;i++)
			  b[i]=a[m+i+1];
                i=0;j=0;k=l;
				while (i<n1 && j<n2)      // 比较完全拆分后数的大小
				{
					if (f[i]<b[j])
						a[k++]=f[i++];
					else
						a[k++]=b[j++];
				}
				while (i<n1)
					a[k++]=f[i++];
				while (j<n2)
					a[k++]=b[j++];
	}
void sort (int a[],int l,int r)    //将数组拆分(递归)
{
	int m;
	m=(l+r)/2;
	if (l<r)
	{
       sort (a,l,m);               
	   sort (a,m+1,r);
	   mer (a,l,m,r);
	}
}
int main ()
{
	int a[100];
	int n,i;
	scanf ("%d",&n);
	for (i=0;i<n;i++)
		scanf ("%d",&a[i]);
	sort (a,0,n-1);
	for (i=0;i<n;i++)
		printf ("%d ",a[i]);
	printf ("\n");
    return 0;
}

    原文作者:递归与分治算法
    原文地址: https://blog.csdn.net/kavu1/article/details/47300549
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞