【问题标题】:quick sort in C++C++中的快速排序
【发布时间】:2016-05-01 02:14:20
【问题描述】:

我正在实现Cormen's Algorithm book(CLRS)中的快速排序算法,但它总是提示“偏移超出范围”,我不知道如何解决它。 这是我的代码。

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

提前致谢!

【问题讨论】:

    标签: c++ algorithm quicksort


    【解决方案1】:

    当你的partition()中,first等于底层序列的begin(),那么:

        auto less_end = first - 1;
    

    变成未定义的行为。

    这很可能是您的问题。如果没有,请使用您的调试器一次单步执行您的代码,直到遇到错误,然后使用您的调试器找出事情在哪里以及为什么会偏离轨道。这就是调试器的用途。

    【讨论】:

      【解决方案2】:

      正如 Sam Varshavchik 在his answer 中已经指出的那样,从 first-1 开始就是问题所在。最简单的解决方案:只需将整个事物移动一个,即从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;
      }
      

      http://rextester.com/JCDUL96865

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-29
        • 2017-02-18
        • 2010-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-17
        相关资源
        最近更新 更多