簡體   English   中英

用C ++快速排序

[英]quick sort in C++

我正在實現Cormen算法書(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;
}

提前致謝!

當在partition()first等於基礎序列的begin()時,則:

    auto less_end = first - 1;

成為未定義的行為。

這可能是您的問題。 如果不是這樣,請使用調試器一次一行地遍歷代碼,直到遇到錯誤為止,然后使用調試器找出問題出在何處和原因。 這就是調試器的用途。

正如Sam Varshavchik在回答中指出的那樣,從頭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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM