1、简介
sort函数是algorithm中的一个函数,其内部采用快速排序实现。因较快的速度而且便于使用,它广泛被应用在需要排序的地方。
2、用法
sort函数拥有3个参数。第1个参数表示待排序数组的起始排序下标,第2个参数表示待排序数组的结束下标(注意:STL中的函数在填范围时一般都要将结束下标加1,此处一定不能忘记)。第3个参数表示的是排序规则,如果不填,默认就是升序排序。
3、代码示例
1、基础升序排序
#include<iostream>
#include<algorithm> // 不要忘记导入头文件
int a[] = {5, 7, 6, 3};
int main() {
std::sort(a, a + 4 /*此处结束下标加1*/);
for (int i = 0; i < 4; i++) std::cout << a[i] << ' ';
return 0;
}
2、降序排序
#include<iostream>
#include<algorithm>
double a[] = {3.14, 7, 1.14, 5.28};
bool cmp(double /*数组是什么类型这里就填什么类型*/x, double y) {
// x和y此时表示数组中的两个元素
// 返回true表示交换,false表示不交换
return x > y;
/*
此句等价于:
if (x > y) return true;
else return false;
*/
}
int main() {
std::sort(a, a + 4, cmp);
for (i = 0; i < 4; ++i) std::cout << a[i] << ' ';
return 0;
}
3、结构体排序
#include<iostream>
#include<algorithm>
struct Node {
int x, y;
} a[4];
// 排序规则:按x的大小升序排序
bool cmp(Node x, Node y) {
return x.x < y.x;
}
int main() {
a[0].x = 7, a[0].y = 3;
a[1].x = 5, a[1].y = 0;
a[2].x = 4, a[2].y = 6;
a[3].x = 100, a[3].y = -17;
std::sort(a, a + 4, cmp);
for (i = 0; i < 4; ++i) std::cout << a[i] << ' ';
return 0;
}
4、注意点
1、因sort函数的内部采用快速排序实现,所以它进行的是不稳定的排序。在某些要求排序算法稳定的情况下,可以使用归并排序实现。
2、虽然sort函数内部添加了许多的优化,但是其本质上的最坏复杂度还是O()(考试易错点)。