算法之归并排序

一、自顶向下的归并排序

#include <stdio.h>

int b[100];

void mergeSort( int a[],  int l, int r );
void merge( int a[], int l, int m, int r );
void display( int a[], int l, int r );

int
main(int argc, char const *argv[])
{	
	int a[100];
	int n = 0, i;
	scanf("%d", &n);
	for ( i = 0; i < n; ++i)
	{
		scanf("%d", &a[i]);
	}

	mergeSort( a, 0, n-1 );
	display( a, 0, n-1 );

	return 0;
}

void
mergeSort( int a[], int l, int r )	//合并排序
{
	int mid = (l+r)/2;
	if ( r <= l) return;
	mergeSort(a, l, mid );
	mergeSort(a, mid+1, r );
	merge( a, l, (l+r)/2, r );
}

void
merge( int a[], int l, int m, int r )	//二路合并 a, (0, 1, 2), (3, 4)
{
	int i, j, k;
	for ( i = m+1; i > l; --i)
		b[i-1] = a[i-1];
	for ( j = m; j < r; ++j)
		b[r+m-j] = a[j+1];

	/* 此时 i,j = l, r,在合并的过程中相互靠拢 */
	for (k = l; k <= r; ++k)
		if ( b[i] <= b[j] )
			a[k] = b[i++];
		else
			a[k] = b[j--];

}

void
display( int b[], int l ,int r )
{
	int i;
	for ( i = l; i <= r; ++i)
	{
		printf("%d ", b[i]);	
	}
	printf("\n");
}

二 自底向上的归并排序

点赞