#include<iostream>
#include<functional>
using namespace std;
//function可用来表示任意可调用对象, 包括lambda对象
void sort(int *begin, int *end,
function<bool(int, int)> cmp = [](int a, int b){ return a < b; }){
if(begin >= end) return ;
//为了避免极端情况下快排的效率偏低,选择中间的值作为基准值,不进行这步程序也能运行
swap(*begin, *(begin + (end - begin) / 2));
int *L = begin, *R = end - 1;
while(L < R){
//找到右边的小于基准值的数,并与基准值交换
while(L < R && cmp(L[0], R[0])) --R;
swap(*R, *L);
//找到左边的大于基准值的数,并与基准值交换
while(L < R && !cmp(R[0], L[0])) ++L;
swap(*L, *R);
}
sort(begin, L, cmp);
sort(R + 1, end, cmp);
}
bool test(int a, int b){
return a > b;
}
int main(){
{//测试lambda表达式
int arr[] = {3, 4, 6, 2, 9, 8, 0, 7, 5, 1};
sort(begin(arr), end(arr), [](int a, int b){ return a >= b;});
for(auto i: arr){
cout << i << " ";
}
cout << endl;
}
{//测试默认排序
int arr[] = {4, 3, 1, 3, 2, 3, 4};
sort(begin(arr), end(arr));
for(auto i: arr){
cout << i << " ";
}
cout << endl;
}
{//测试自定义比较函数
int arr[] = {3, 4, 1, 5, 2, 6};
sort(begin(arr), end(arr), test);
for(auto i: arr){
cout << i << " ";
}
cout << endl;
}
return 0;
}
c++ sort的简单实现
最新推荐文章于 2023-01-14 20:42:04 发布