我试图用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::greater
的示例输入:
1, 2, 3
预期:
3, 2, 1
实际:
1, 2, 3
答案 0 :(得分: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>());
答案 1 :(得分:2)
一个明显的问题是,您没有将compare
传递给内部Quicksort
,因此大概是它们回到了您的默认情况。
QuickSort(first, bound, compare);
QuickSort(bound, last, compare);