使用 sort() 需包含头文件<algorithm>, 默认升序排列。
sort(begin, end),begin 和 end 分别为待排序数组的首地址和尾地址。
其平均时间复杂度为 O(nlogn)。
自定义排序规则
compare 函数functional 库#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
bool compare(int a, int b){
return a > b; //降序
}
int main()
{
int a[5] = {5, 3, 2, 1, 4};
for(int i = 0; i < 5; ++i)
cout << a[i] << " ";
cout << endl;
sort(a, a+5, compare);
for(int i = 0; i < 5; ++i)
cout << a[i] << " ";
cout << endl;
return 0;
}functional 提供了如下基于模板的比较函数对象:
sort(begin, end, greater<数据类型>()); 降序
sort(begin, end, less<数据类型>()); 升序