简体   繁体   English

用C ++快速排序

[英]quick sort in C++

I am implementing the quick sort algorithm from Cormen's Algorithm book(CLRS), but it always prompt "offset out of range", and I don't know how to fix it. 我正在实现Cormen算法书(CLRS)中的快速排序算法,但是它总是提示“偏移量超出范围”,而且我不知道如何解决。 Here's my code. 这是我的代码。

template<typename Iterator>
void quick_sort(Iterator first, Iterator last)
{
    if (last - first > 1)
    {
        auto pivot = partition(first, last);
        quick_sort(first, pivot);
        quick_sort(pivot + 1, last);
    }
}

template<typename Iterator>
Iterator partition(Iterator first, Iterator last)
{
    auto pivot = last - 1;
    auto less_end = first - 1;
    for (auto iter = first; iter != pivot; ++iter)
    {
        if (*iter <= *pivot)
        {
            std::swap(*++less_end, *iter);
        }
    }
    std::swap(*(less_end + 1), *pivot);
    return less_end + 1;
}

Thanks in advance! 提前致谢!

When, in your partition() , first is equal to the begin() of the underlying sequence, then: 当在partition()first等于基础序列的begin()时,则:

    auto less_end = first - 1;

becomes undefined behavior. 成为未定义的行为。

This is likely to be your problem. 这可能是您的问题。 If not, use your debugger to step through your code a line at a time, until the error is encountered, and use your debugger to figure out where and why things go off the rails. 如果不是这样,请使用调试器一次一行地遍历代码,直到遇到错误为止,然后使用调试器找出问题出在何处和原因。 That's what a debugger is for. 这就是调试器的用途。

As Sam Varshavchik has already pointed out in his answer , starting at first-1 is the problem. 正如Sam Varshavchik在回答中指出的那样,从头1开始就是问题所在。 Simplest solution: just shift the whole thing by one, ie start at first , post- instead pre-increment and so on..... 简单的解决办法:只需一个班次整个事情,即在开始first ,而不是后预增等等.....

template<typename Iterator>
Iterator partition(Iterator first, Iterator last)
{
    auto pivot = last - 1;
    auto less_end = first;
    for (auto iter = first; iter != pivot; ++iter)
    {
        if (*iter <= *pivot)
        {
            std::swap(*less_end++, *iter);
        }
    }
    std::swap(*(less_end), *pivot);
    return less_end;
}

see http://rextester.com/JCDUL96865 参见http://rextester.com/JCDUL96865

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM