归并算法

归并算法代码
#include <iostream>
using namespace std;

void Merger(int32_t numList[], int32_t first, int32_t mid, int32_t last) {
    int32_t tmpList[13];
    auto indexA = first; 
    auto indexB = mid + 1; 
    auto index = 0;

    //在没有比较完两个子标的情况下,比较 numList[indexA]和numList[indexB]
    //将其中小的放到临时变量tmpList中
    while (indexA <= mid && indexB <= last) {
        if (numList[indexA] < numList[indexB]) {
            tmpList[index++] = numList[indexA];
            indexA++;
        } else {
            tmpList[index++] = numList[indexB];
            indexB++;
        }
    }

    //复制没有比较完子表中的元素
    while (indexA <= mid) {
        tmpList[index++] = numList[indexA];
        indexA++;
    }

    while (indexB <= last) {
        tmpList[index++] = numList[indexB];
        indexB++;
    }

    for (auto i = 0; i < index; i++) {
        numList[first + i] = tmpList[i];
    }
}

void MergerSort(int32_t numList[], int32_t first, int32_t last) {
    if (first < last) { 
        auto mid = (first + last) / 2;
        MergerSort(numList, first, mid);
        MergerSort(numList, mid + 1, last);
        Merger(numList, first, mid, last);
    }
}

void main() {
    int32_t numList[] = { 31, 41, 59, 26, 48, 58, 12, 5, 90, 10, 9, 6, 45};
    int32_t count = sizeof(numList) / sizeof(numList[0]);
    MergerSort(numList, 0, count-1);

    for (auto num : numList) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
}

返回排序算法分析总结

参考文章:递归算法学习系列二(归并排序)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值