我尝试执行 this在 C++ 中使用迭代器编写代码。它适用于例如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
最佳答案
快速排序:
/*
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>());
结果:
关于c++ - 如何使用迭代器格式实现快速排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54974729/