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

gives incorrect results,Is my implementation wrong?Well, is the algorithm supposed to give incorrect results?QuickSort(bound, last);should beQuickSort(bound + 1, last);for instance.