排序算法之归并排序

<pre name="code" class="cpp">// MergeSort.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
// SelectSort.cpp : Defines the entry point for the console application.
//
#include "iostream"
using namespace std;

// 归并排序:假设序列含义n 个记录,则可以看成是n 个长度均为1 的有序子序列(长度为1,当然有序), 然后两两归并,得到n/2 个长度为2 和 (n/2 - [n/2])个长度为1 的子序列([x]表示向上取整),
// 继续两两归并,直到得到长度为n 的有序序列为止;

// 将x[s..m], s[m+1,...t] 归并到 r[s...t]
void Merge(double x[], double r[], int s, int m, int t)
{
	// 将r[s..m] 和 r[m+1, ...,t] 归并为 a[s..t];
	int i = 0;
	int j = 0;
	int k = s;
	for (i=s, j=m+1; i<=m && j<=t; NULL)
	{
		if (x[i] < x[j])
		{
			r[k++] = x[i++];
		}
		else
		{
			r[k++] = x[j++];
		}
	}

	// 将剩余的拷贝, 下面两个for 循环,最终只执行一次;
	for (NULL; i<=m; NULL)
	{
		r[k++] = x[i++];
	}

	for (NULL; j<=t; NULL)
	{
		r[k++] = x[j++];
	}
}

void MergeSortSub(double a[], double r[], int s, int t, int n)
{
	if (s == t)
	{
		r[s] = a[s];
	}
	else
	{
		double *p = new double[n];

		int m = (s + t) / 2;
		// a[s...m] 归并到有序子序列p[s...m];
		MergeSortSub(a, p, s, m, n);
		// a[m+1...t] 归并到有序子序列p[m+1,...t];
		MergeSortSub(a, p, m + 1, t, n);
		// 将p[s..m], s[m+1,...t] 归并到 r[s...t]
		Merge(p, r, s, m, t);

		delete[] p;
		p = NULL;
	}
}

void MergeSort(double a[], int n)
{
	MergeSortSub(a, a, 0, n- 1, n);
}


int _tmain(int argc, _TCHAR* argv[])
{
	double a[] = {2.0, 5.4, 4.0, 8.0, 3.0, 5.0, 1.0, 9.0, 7.0};
	int n = sizeof(a) / sizeof(*a);

	cout<<"排序前:\n";
	for each (double x in a)
	{
		cout<<x<<" ";
	}
	cout<<endl;

	MergeSort(a, n);

	cout<<"排序后:\n";
	for each (double x in a)
	{
		cout<<x<<" ";
	}
	cout<<endl;

	return 0;
}




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值