排序-----归并排序

/*归并排序是利用归并的思想,采用分治策略,将问题分为一些小问题然后递归求解。在治阶段将分阶段得到****的各答案合在一起。比如一个{8,4,5,7,1,3,6,2}的数列分成{8,4,5,7}和{1,3,6,2}之后
****再分成{8,4},{5,7},{1,3},{6,2}再分成{8}{4}{5}{7}{1}{3}{6}{2},然后开始比较先比较8,4
****小的放前面之后合并,{4,8},以此类推合并{5,7},{1,3},{2,6}再比较合并{4,5,7,8},{1,****2,3,6},再比较合并{1,2,3,4,5,6,7,8}.
****归并是稳定排序,时间复杂度nlogn。
*/
#include <stdio.h>
#include<malloc.h>
//using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
//template<class Type>
//合并
void Merge(int A[], int TmpAry[], int Lpos, int Rpos, int RightEnd)
{
	int i, LeftEnd, NumTypes, TmpPos; 
	LeftEnd = Rpos - 1;
	TmpPos = Lpos;     //临时数组指针
	NumTypes = RightEnd - Lpos + 1;
	while (Lpos <= LeftEnd&&Rpos <= RightEnd)
	{
		if (A[Lpos] <= A[Rpos])
		{
			TmpAry[TmpPos++] = A[Lpos++];
		
		}
			
		else
		{
			TmpAry[TmpPos++] = A[Rpos++];
			
		}
			

	}
	
	while (Lpos <= LeftEnd)
	{
		TmpAry[TmpPos++] = A[Lpos++];
		
	}
		
	while (Rpos <= RightEnd)
	{
		TmpAry[TmpPos++] = A[Rpos++];
		
	}
		
	//复制
	for (i = 0; i<NumTypes; i++, RightEnd--)
		A[RightEnd] = TmpAry[RightEnd];
	


}
void MSort(int A[], int TmpAry[], int left, int right)
{
	if (left<right)
	{
		int center = (left + right) / 2;
		MSort(A, TmpAry, left, center);//处理左半部
		MSort(A, TmpAry, center + 1, right);//处理右半部分
		Merge(A, TmpAry, left, center + 1, right);//合并
		
	}
}
//测试
void MergeSort(int A[], int N)
{
	int *TmpAry;
	TmpAry = (int*)malloc(N*sizeof(int));
	if (TmpAry != NULL)
	{
		MSort(A, TmpAry, 0, N - 1);
		free(TmpAry);
	}
	else
		printf("ERROR");
	//cout<<"not space for tem array!"<<endl;
}

int main(int argc, char *argv[]) {
	int i;
	int A[8] = { 6,3, 1, 2, 12, 32,16,89 };
	MergeSort(A, 8);
	for (i = 0; i<8; i++)
		//cout<<A[i]<<endl;
		printf("%d\n", A[i]);
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值