Ava
Ava

Reputation: 838

How to implement quicksort using iterator format?

I tried to implement this code with iterators in C++. It works fine for e.g. std::less<>() as comparator but gives incorrect results when using std::greater<>(). Is my implementation wrong?

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

Edit:

Example input, using std::greater: 1, 2, 3 Expected: 3, 2, 1 Actual: 1, 2, 3

Upvotes: 0

Views: 2674

Answers (2)

Caleth
Caleth

Reputation: 63019

There's the obvious problem that you aren't passing the compare to the inner Quicksorts, so presumably they are falling back to your default case.

QuickSort(first, bound, compare);
QuickSort(bound, last, compare);

Upvotes: 2

Kinght 金
Kinght 金

Reputation: 18331

QuickSort:

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

Test code:

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>());

Result:

enter image description here

Upvotes: 4

Related Questions