归并算法

本文详细介绍了一种高效的排序算法——归并排序,并通过具体的C++代码实现了该算法。通过对数组进行分治处理,归并排序能有效地将多个已排序的子数组合并成一个有序数组。文中提供了一个完整的示例,展示了如何对一个整数数组进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

归并算法代码
#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;
}

返回排序算法分析总结

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值