mergeSort

归并排序是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,

每个子序列是有序的。然后再把有序子序列合并为整体有序序列。归并排序是一种稳定的排序算法。  

若将两个有序表合并成一个有序表,称为2-路归并。

归并排序采用经典的分治策略,同时也是分析递归例程的经典实例。实现代码如下。

/************************************************
*** heapSort.c 
*** 归并排序的实现
*************************************************/
#include <stdio.h>
#include <stdlib.h>

void mergeSort( int A[], int n );
void MSort( int A[], int tmpArray[], int nLeft, int nRight );
void merge( int A[], int tmpArray[], int nLpos, int nRpos, int nRightEnd );

void mergeSort( int A[], int n )
{
	int *tmpArray;

	tmpArray = malloc( n * sizeof( int ) );
	if ( NULL != tmpArray )
	{
		MSort( A, tmpArray, 0, n - 1 );
		free( tmpArray );
	}
	else
	{
		printf("Out of memory!\n");
	}
}

void MSort( int A[], int tmpArray[], int nLeft, int nRight )
{
	int nCenter = ( nLeft + nRight ) / 2;

	if ( nLeft < nRight )
	{
		MSort( A, tmpArray, nLeft, nCenter );	/** 使左边部分数组有序 **/
		MSort( A, tmpArray, nCenter + 1, nRight );	/** 使右边边部分数组有序 **/
		merge( A, tmpArray, nLeft, nCenter + 1, nRight );	/** 合并两个有序数组,实现归并排序效果 **/
	}
}

void merge( int A[], int tmpArray[], int nLpos, int nRpos, int nRightEnd )
{
	int    nLeftEnd = 0;
	int     nTmpPos = 0;
	int		      i = 0;
	int	nNumElement = 0;	

	nLeftEnd = nRpos - 1;
	nTmpPos  = nLpos;
	nNumElement = nRightEnd - nLpos + 1;

	while ( nLpos <= nLeftEnd && nRpos <= nRightEnd )	/** 合并两个有序数组 **/
	{
		/**
		*** 选取两个有序数组较小数存到临时数组
		**/
		if ( A[nLpos] < A[nRpos] )
		{
			tmpArray[nTmpPos++] = A[nLpos++];
		}
		else
		{
			tmpArray[nTmpPos++] = A[nRpos++];
		}
	}

	/**
	*** 复制两个有序数组中未选取到的一组数的一部分
	**/
	while ( nLpos <= nLeftEnd )
	{
		tmpArray[nTmpPos++] = A[nLpos++];
	}
	while ( nRpos <= nRightEnd )
	{
		tmpArray[nTmpPos++] = A[nRpos++];
	}

	/**
	*** 将临时数组逆序复制到原数组
	**/
	for (i=0; i<nNumElement; i++, nRightEnd--)
	{
		A[nRightEnd] = tmpArray[nRightEnd];
	}
}

int main()
{
	int i = 0;
	int n = 13;
	int nArray[13] = {81, 94, 11, 96, 12, 35, 17, 95, 28, 58, 41, 75, 15};

	printf("The arrry before mergeSort is: \n");
	for (i=0; i<n; i++)
	{
		printf("%d ", nArray[i]);
	}
	printf("\n\n");
	
	mergeSort( nArray, n );	/** 调用归并排序 **/

	printf("The arrry after mergeSort is: \n");
	for (i=0; i<n; i++)
	{
		printf("%d ", nArray[i]);
	}
	printf("\n");

	return	0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值