zoukankan      html  css  js  c++  java
  • 快速排序

    快速排序

    该算法的思想是:给定一个列表,选取一个数作为“中间值”,之后将列表中的其他值分成两组,一组大于中间值,一组小于中间值;然后对小于“中间值”的组进行排序,返回排好序的列表,对大于“中间值”的一组进行排序,返回排好序的列表。

    顺序版

    #include <iostream>
    #include <list>
    #include <algorithm>
    
    template<typename T>
    std::list<T> quick_sort(std::list<T> input) {
        if (input.empty())  {
            return input;
        }
        std::list<T> result;
        result.splice(result.end(), input, input.begin()); // 1.选取列表第一个数作为主元
        auto pivot = *result.begin();
        auto divide_point = std::partition(input.begin(), input.end(),
                [&](const T& t){ return t < pivot;} );
        std::list<T> lower_part;
        lower_part.splice(lower_part.begin(), input, input.begin(), divide_point);
        std::list<T> new_lower( quick_sort(std::move(lower_part)) );
        std::list<T> new_higher( quick_sort(std::move(input)) );
        result.splice(result.begin(), new_lower);
        result.splice(result.end(), new_higher);
        return result;
    }
    
    
    void test() {
        std::list<int> l{5,9,6,11,8,4,5,2,4,2,3};
        auto ret = quick_sort(l);
        for (auto x : ret) {
            std::cout << " " << x;
        }
        std::cout << std::endl;
    }
    
    int main() {
        test();    // 2 2 3 4 4 5 5 6 8 9 11
        return 0;
    

    线程强化版

    #include <iostream>
    #include <list>
    #include <future>
    #include <algorithm>
    
    template<typename T>
    std::list<T> parallel_quick_sort(std::list<T> input) {
        if (input.empty())  {
            return input;
        }
        std::list<T> result;
        result.splice(result.end(), input, input.begin()); // 1.选取列表第一个数作为主元
        auto pivot = *result.begin();
        auto divide_point = std::partition(input.begin(), input.end(),
                [&](const T& t){ return t < pivot;} );
        std::list<T> lower_part;
        lower_part.splice(lower_part.begin(), input, input.begin(), divide_point);
    
        std::future<std::list<T>> new_lower(  // 2.
            std::async(&parallel_quick_sort<T>, std::move(lower_part)));
        std::list<T> new_higher( parallel_quick_sort(std::move(input)) );
    
        result.splice(result.end(), new_higher);
        result.splice(result.begin(), new_lower.get());  // 3.
        return result;
    }
    
  • 相关阅读:
    书到用时方恨少---记录读书历程
    JAVASCRIPT数据类型(值类型-引用类型-类型总览)
    jQuery基本API小结(下)---工具函数-基本插件
    jQuery基本API小结(上)--选择器-DOM操作-动画-Ajax
    【转】javascript 执行环境,变量对象,作用域链
    JavaScript知识总结--对象的相关概念
    JavaScript知识总结--引用类型(Object-Array-Function-Global-Math)
    JavaScript知识总结--历史-html引用方式-基础概念
    Java--神奇的hashcode
    Java-从堆栈常量池解析equals()与==
  • 原文地址:https://www.cnblogs.com/codemeta-2020/p/12461908.html
Copyright © 2011-2022 走看看