计算机算法设计与分析第四版[王]
2.7合并排序
#include<iostream>
using namespace std;
template<class type>
void MergePass(type x[], type y[], int s, int n)
{
int i = 0;//合并大小为s的相邻2段子数组
while (i <= n - 2 * s)
{
Merge(x, y, i, i + s - 1, i + 2 * s - 1);
i = i + 2 * s;
}//剩下的元素个数少于2s
if (i + s < n) Merge(x, y, i, i + s - 1, n - 1);;//剩下的长度大于一个归并段
else for (int j = i;j <= n - 1;j++) y[j] = x[j];//剩下的长度小于一个归并段
}
template<class type>
void Merge(type c[], type d[], int l, int m, int r)
{
//合并c[1:m] 和c[m+1:r]到d[l:r]
int i = l, j = m + 1, k = l;
while ((i <= m) && (j <= r))
{
if (c[i] <= c[j]) d[k++] = c[i++];
else d[k++] = c[j++];
}
if (i <= m)for (int q = i;q <= m;q++) d[k++] = c[q];
else for (int q = j;q <= r;q++) d[k++] = c[q];
}
template<class type>
void MergeSort(type a[], int n)
{
type *b = new type[n];
int s = 1;//初始合并段宽度
while (s < n)
{
MergePass(a, b, s, n);//合并到数组b
s += s;
MergePass(b, a, s, n);//合并的数组a
s += s;
}
}
int main()
{
int a[] = { 1000,55,654,12,333,66666,2,548,22,996,24,11,5 };
MergeSort(a, 13);
for (int i = 0;i < 2;i++)
{
cout << a[i] << endl;
}
}
此方法是直接的使用归并排序是思想,按照分段大小,两端两端的合并即可。