归并排序C++

本文介绍了归并排序(MergeSort)的基本原理和分治策略,通过C++代码展示了如何实现归并排序的过程,包括如何递归地将数组分成两部分并进行排序,以及如何合并两个已排序的子数组。此外,还提供了打印输出排序结果的辅助函数。

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

本篇文章参考《大话数据结构》一书

归并排序(Merge Sort)是利用归并的思想实现的排序方法,该算法采用经典的分治(divide-and-conquer)策略将问题分成一些小的问题然后递归求解,即分而治之。

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

#define initial_capacity 10
//归并排序
class Solution
{
public:

    vector<int> merge_sort(vector<int>& ans)
    {
        vector<int>res;
        res.resize(initial_capacity); //需要预先设置起始容量,防止越界
        int s = 0, t = ans.size() - 1;
        mySort(ans, res, s, t); 
        return res;
    }

    void mySort(vector<int>& ans, vector<int>& res, int s, int t)
    {
        vector<int>temp;
        temp.resize(initial_capacity);
        if (s == t)
            res[s] = ans[s];
        else
        {
            int m = (s + t) / 2;          //将ans数组平分为两个数组
            mySort(ans, temp, s, m);      //递归地将前数组归并为有序的temp数组
            mySort(ans, temp, m + 1, t);  //递归地将后数组归并为有序的temp数组
            myMerge(temp, res, s, m, t);  //将前两个数组归并为res有序数组
        }
    }

    void myMerge(vector<int>& ans, vector<int>& result, int i, int m, int n)
    //m,n分别为中间位置以及尾部位置
    {
        int j, k, l;
        for (j = m + 1, k = i; i <= m && j <= n; k++)
        {
            if (ans[i] < ans[j])
            {
                result[k] = ans[i++];
            }
            else
            {
                result[k] = ans[j++];
            }
        }

        //如果此时前数组未结束,而后数组结束时,将前数组剩余内容依次追加到结果数组
        if (i <= m)
        {
            for (l = 0; l <= m - i; l++)
            {
                result[k + l] = ans[i + l];
            }
        }

        //与上述反之
        if (j <= n)
        {
            for (l = 0; l <= n - j; l++)
            {
                result[k + l] = ans[j + l];
            }
        }

    }
};

//打印输出
void myPrint(vector<int>& ans)
{
    for (int i = 0; i < ans.size(); i++)
    {
        cout << ans[i] << "  ";
    }
    cout << endl;
}

int main()
{
    vector<int>ans = { 1,12,3,9,5,4,0,1,8,7 };

    Solution s;
    auto a = s.merge_sort(ans);
    myPrint(a);      //打印输出

    system("pause");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值