归并排序-非递归版

计算机算法设计与分析第四版[王]

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;
    }
}

此方法是直接的使用归并排序是思想,按照分段大小,两端两端的合并即可。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值