• 归并排序


    归并的意思是: 先递拆分排序,再合每个小的(相临的)数组。

    下面是代码(C++14)

    #include <iostream>
    #include <vector>
    #include <deque>
    #include <iterator>
    #include <algorithm>
    
    using std::cout;
    using std::endl;
    using std::copy;
    using std::vector;
    using std::deque;
    using std::ostream_iterator;
    
    template <typename OS, typename C>
    OS & Print(OS & os, const C & c)
    {
        using T = typename C::value_type;
        copy(begin(c), end(c), ostream_iterator<T>(os, "	"));
        return os;
    }
    
    template <typename C, typename ST = typename C::size_type>
    void Merge(C & c, ST first, ST middle, ST last)
    {
        ST  f = first,
            m = middle + 1,
            k = 0;
    
        C temp (last - first);
    
        // 合并的时候排序
        while (f <= middle && m <= last)
        {
            if (c[f] < c[m])
            {
                temp[k++] = c[f++];
            }
            else
            {
                temp[k++] = c[m++];
            }
        }
    
        // 两段区间, 谁还没复制完, 继续
        while (f <= middle)
        {
            temp[k++] = c[f++];
        }
    
        while (m <= last)
        {
            temp[k++] = c[m++];
        }
    
        // 把 temp 复制回 c, 覆盖 c 中的[first, last] 区域
        // (因为 temp 就是 c 中这个区域 已经排序的值)
        copy_n(temp.begin(), k, c.begin() + first);
    }
    
    // 排序实际上是最简单的, 也就是个递归操作: 分别对前后两部分进行排序, 然后再合并
    template <typename C, typename ST = typename C::size_type>
    void Sort(C & c, ST first, ST last)
    {
        if (first < last)
        {
            ST mid = (first + last) / 2;
            Sort(c, first, mid);
            Sort(c, mid + 1, last);
            Merge(c, first, mid, last);
        }
    }
    
    int main()
    {
        vector<int> vi {10, 9, 8, 15, 7, 24, 5, 4, 2, 95};
        Print(cout, vi) << endl;
        Sort(vi, (vector<int>::size_type)0, vi.size() - 1);
        Print(cout, vi) << endl << "--------------" << endl;
    
        deque<double> di {1.0, 9.4, 3.88, 1.5, 7.8, 2.4, 5.9, 4.2, 2.8, 9.5};
        Print(cout, di) << endl;
        Sort(di, (deque<int>::size_type)0, vi.size() - 1);
        Print(cout, di) << endl << "--------------" << endl;
    }
  • 相关阅读:
    mysql存储过程详细教程
    js timestamp与datetime之间的相互转换
    spring集成httpclient配置
    Spring使用@scope("session")爆org.springframework.beans.factory.UnsatisfiedDependencyException
    算术编码Arithmetic Coding-高质量代码实现详解
    String Reduction
    (转)Maximum subarray problem--Kadane’s Algorithm
    判断一个字符串在至多删除k个字符后是否为回文串
    最小区间使得至少包含每组元素中的一个
    Pots of gold game:看谁拿的钱多
  • 原文地址:https://www.cnblogs.com/typename/p/4634084.html
Copyright © 2020-2023  润新知