#include<iostream>
#include<vector>
using namespace std;
template<typename Iter, typename Compare>
void quick_sort(Iter begin, Iter end, Compare comp) {
if (distance(begin, end) <= 1) //如果长度为1则无需排序
return;
Iter low = begin;
Iter high = end - 1;
_Iter_value_t<Iter>& base = *begin;
while (low < high) {
while (low < high && !comp(*high, base)) { //从末尾找小值
--high;
}
while (low < high && !comp(base, *low)) { //从起始找大值
++low;
}
if (low < high) //找到就交换
swap(*(low), *(high));
}
swap(*low, base); //更新轴值
quick_sort(begin, low, comp); //对左侧排序
quick_sort(low + 1, end, comp); //对右侧排序
}
template<typename Iter>
void quick_sort(Iter begin, Iter end) {
quick_sort(begin, end, less<_Iter_value_t<Iter>>());
}
int main() {
vector<int> a = { 6 , 1 ,2 ,7 ,3, 3 ,4 , 5 ,10 , 8 };
quick_sort(a.begin(), a.end());
return 0;
}
C++快速排序模板——支持迭代器,lambda表达式、仿函数。
猜你喜欢
转载自blog.csdn.net/qq_40946921/article/details/108561380
今日推荐
周排行