如何使用迭代器格式实现快速排序?

问题描述 投票:0回答:2

我试图用C ++中的迭代器实现this代码。它适用于例如std :: less <>()作为比较器,但在使用std :: greater <>()时给出的结果不正确。我的实施错了吗?

template <typename RandomIt, typename Compare>
void QuickSort(RandomIt first, RandomIt last, Compare compare)
{
    if (std::distance(first, last) <= 1) return;
    RandomIt bound = Partition(first, last, compare);
    QuickSort(first, bound);
    QuickSort(bound, last);
}

template <typename RandomIt, typename Compare>
RandomIt Partition(RandomIt first, RandomIt last, Compare compare)
{
    auto pivot = std::prev(last, 1);
    auto i = first;
    for (auto j = first; j != pivot; ++j)
        if (compare(*j, *pivot))
            std::swap(*i++, *j);
    std::swap(*i, *pivot);
    return i;
}

编辑:

示例输入,使用std::greater1, 2, 3预计:3, 2, 1实际:1, 2, 3

c++ algorithm sorting quicksort
2个回答
2
投票

快速排序:

/*
Description : QuickSort in Iterator format
Created     : 2019/03/04 
Author      : Knight-金 (https://stackoverflow.com/users/3547485)
Link        : https://stackoverflow.com/a/54976413/3547485

Ref: http://www.cs.fsu.edu/~lacher/courses/COP4531/lectures/sorts/slide09.html
*/

template <typename RandomIt, typename Compare>
void QuickSort(RandomIt first, RandomIt last, Compare compare)
{
    if (std::distance(first, last)>1){
        RandomIt bound = Partition(first, last, compare);
        QuickSort(first, bound, compare);
        QuickSort(bound+1, last, compare);
    }
}

template <typename RandomIt, typename Compare>
RandomIt Partition(RandomIt first, RandomIt last, Compare compare)
{
    auto pivot = std::prev(last, 1);
    auto i = first;
    for (auto j = first; j != pivot; ++j){
        // bool format 
        if (compare(*j, *pivot)){
            std::swap(*i++, *j);
        }
    }
    std::swap(*i, *pivot);
    return i;
}

测试代码:

std::vector<int> vec = {0, 9, 7, 3, 2, 5, 6, 4, 1, 8};

// less 
QuickSort(std::begin(vec), std::end(vec), std::less<T>());

// greater 
QuickSort(std::begin(vec), std::end(vec), std::greater<int>());

结果:

enter image description here


2
投票

有一个明显的问题,你没有将compare传递给内部Quicksorts,所以可能他们会回到你的默认情况。

QuickSort(first, bound, compare);
QuickSort(bound, last, compare);
© www.soinside.com 2019 - 2024. All rights reserved.