归并排序

#include <iostream>
#include <algorithm>
using namespace std;

//initList:初始数组
//mergeList:合并之后的数组
//l:数组的下标
//m:数组的下标
//n:一共有多少个数要合并
template <typename T>
void Merge(T *initList, T *mergedList, const int l, const int m, const int n)
{
    //i1,i2: 用来对两个数组进行循环
    //iResult:对归并以后的数组进行循环
    int i1, i2, iResult;
    for (i1 = l, i2 = m + 1, iResult = l; i1 <= m && i2 <= n; iResult++)
    {
        if (initList[i1] <= initList[i2])
        {
            mergedList[iResult] = initList[i1];
            i1++;
        }
        else
        {
            mergedList[iResult] = initList[i2];
            i2++;
        }
        
    }
    copy(initList + i1, initList + m + 1, mergedList + iResult);
    copy(initList + i2, initList + n + 1, mergedList + iResult);

}

//initList:初始数组
//mergeList:归并之后的数组
//n:参与排序的总的元素个数
template<class T>
void MergePass(T *initList, T *resultList, const int n, const int s)
{
    int i;
    for (i = 1; i <= n - 2 * s + 1; i += 2 * s)
    {
        Merge(initList, resultList, i, i + s - 1, i + 2 * s - 1);
    }
    if ((i + s - 1) < n)
    {
        Merge(initList, resultList, i, i + s - 1, n);
    }
    else
    {
        copy(initList + i, initList + n + 1, resultList + i);
    }
}

template<class T>
void MergeSort(T *a, const int n)
{
    int *tempList = new int[n + 1];//tempList[0]不用
    for (int l = 1; l < n; l *= 2)
    {
        MergePass(a, tempList, n, l);
        l *= 2;
        MergePass(tempList, a, n, l);
    }

    delete[] tempList;
}
int main()
{
    //a[0]为废弃元素
    int a[] = { 0, 23, 47, 81, 95, 7, 14, 39, 55, 62, 74 };
    int b[11] = { 0 };
    Merge(a, b, 1, 4, 10);
    for (int i = 1; i < 11; ++i)
    {
        cout << b[i] << " ";
    }
    std::cout << endl;

    int m[] = { 0, 26, 5, 77, 1, 61, 11, 59, 15, 48, 19 };

    //分解测试
    int n[11] = { 0 };//存放每次归并的结果
    MergePass(m, n, 10, 1);
    for (int i = 1; i < 11; i++)
    {
        cout << n[i] << " ";
    }
    std::cout << endl;

    MergePass(n, m, 10, 2);
    for (int i = 1; i < 11; i++)
    {
        cout << m[i] << " ";
    }
    std::cout << endl;

    MergePass(m, n, 10, 4);
    for (int i = 1; i < 11; i++)
    {
        cout << n[i] << " ";
    }
    std::cout << endl;

    MergePass(n, m, 10, 8);
    for (int i = 1; i < 11; i++)
    {
        cout << m[i] << " ";
    }
    std::cout << endl;
    cout << "上面为中间过程分解" << endl;
    cout << "下面为正式归并算法" << endl;

    int x[] = { 0, 26, 5, 77, 1, 61, 11, 59, 15, 48, 19 };

    MergeSort(x, 10);

    for (int i = 1; i < 11; i++)
    {
        cout << x[i] << " ";
    }
    std::cout << endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值