首页 > 编程语言 > 详细

快速排序

时间:2020-03-11 14:31:45      阅读:57      评论:0      收藏:0      [点我收藏+]

快速排序

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

顺序版

#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;
}

快速排序

原文:https://www.cnblogs.com/codemeta-2020/p/12461908.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!