c++ - 如何使用 C++ 库算法分区函数进行快速排序?

标签 c++ algorithm

我正在尝试使用 C++ 库分区函数执行快速排序,这是我的代码

int p;
int pred(int x)
{
    return x<=p;
}

    void quickSort(vector<int>::iterator first,vector<int>::iterator last) {
    if(first == last)
        return;
    if((first+1) == last)
        return;
    p = *first;
    auto mid = partition(first,last,pred);
    quickSort(first,mid);
    quickSort(mid,last);
    --mid;
    swap(*mid,*first);
    for(auto itr = first;itr!=last;++itr)
        cout<<(*itr)<<" ";
    cout<<endl;
}

它在分区函数中给出了 segFault。我想使用库函数。

最佳答案

这个使用 lambda:

void quick(std::vector<int>::iterator first, std::vector<int>::iterator last)
{
    if (first == last) return;

    auto pivot = *first;
    auto mid = std::partition(first, last, [pivot](int i){return pivot > i;});
    if (mid == last) return;
    quick(first, mid);
    quick(++mid, last);
}

关于c++ - 如何使用 C++ 库算法分区函数进行快速排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20990894/

相关文章:

c++ - SSE/优化 - 将数组复制到更大的数组

c++ - "Live"代码和使用 C++ 和 LLVM JIT 的快速原型(prototype)制作?

x86 上的 C 64 位循环性能

java - 在Java中查找负数的最大乘积

c++ - PRO*C 和 C++ 中的数据类型冲突

c++ - 将负数分配给无符号整数

algorithm - 快速傅里叶变换多项式乘法?

algorithm - 线性搜索算法的平均情况运行时间

javascript - 在网格上查找空白空间的算法

c++ - boost:asio::read 或 boost:asio::async_read 超时