<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;
}
排序算法之归并排序
最新推荐文章于 2024-10-19 23:06:28 发布