0
点赞
收藏
分享

微信扫一扫

C++十行代码的快速排序-C++11

星巢文化 2022-03-21 阅读 68

全部使用C++11新特性,使用递归方法,FP式编程。

template<typename T>
list<T> sequential_quick_sort(list<T> input)
{
    if(input.empty())
    {
        return input;
    }
    list<T> result;
    // 将input中的input.begin()这个元素转移到result.begin()的位置
    // 不是复制或移动元素,而是重指向链表节点的内部指针,原指针实效,被移除
    // 所以可以把solice勉强的看成是可移动的
    result.splice(result.begin(),input,input.begin());
    // 使用引用,避免复制,中轴值
    const T &pivot = *result.begin();
    // 将序列划分成小于中轴值的和不小于中轴值的,返回第一个不小于中轴值的迭代起
    auto divide_point = partition(input.begin(),input.end(),[&](const T &t){
        return t < pivot;
    });
    // 新建一个存放小于的容器,大于等于的可以存放在原容器
    list<T> lower_part;
    // 将序列小于中轴值的部分转移到lower_part列表
    // 这样lower_part全是小于中轴值的元素,input还剩下大于等于中轴值的元素
    lower_part.splice(lower_part.end(),input,input.begin(),divide_point);
    // 使用递归分别对小于中轴值的序列进行同样的操作,使用移动,防止拷贝
    auto new_lower(sequential_quick_sort(move(lower_part)));
    // 使用递归对大于等于中轴值的序列进行同样的操作,使用移动,防止拷贝
    auto new_higher(sequential_quick_sort(move(input)));
    // 最后将结果进行正确的拼接,把大于等于的部分拼接到中轴值的后面
    result.splice(result.end(),new_higher);
    // 把小于的部分,拼接到中轴值的前面
    result.splice(result.begin(),new_lower);
    // 返回最终结果
    return result;
}
举报

相关推荐

0 条评论