sort函数是C++标准库的排序函数,其效率很高(高于冒泡排序),时间复杂度为n*log(n)
使用方法
1.其头文件为#include<algorithm>
2.sort函数有三个参数:
1)第一个,排序的起始地址
2)第二个,排序的结束地址
3)排序方法,升序或降序,若不写第三个参数,则默认为升序。
3.使用模板sort(begin,end,cmp);
cmp为排序方式
排序函数的写法
升序写法
//升序
bool cmp1(int a, int b)
{
return a < b;
}
降序写法
//降序
bool cmp2(int a, int b)
{
return a > b;
}
C++自定义排序规则:
less<数据类型> //升序
greater<数据类型> //降序
例:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a[10] = {2, 4, 1, 3, 6, 5, 7, 9, 8, 0}, i;
sort(a, a + 10, less<int>());
for (i = 0; i < 10; i++)
cout << a[i] << " ";
cout << "\n";
return 0;
}
自定义数据类型写法:
// by LMY
#include <bits/stdc++.h>
using namespace std;
class number
{
public:
int height;
int width;
};
bool cmp3(number a, number b)
{
return a.height > b.height;
}
int main()
{
int i, h, w;
number a[5];
cout << "请输入数据\n";
for (i = 0; i < 5; i++)
{
cin >> h >> w;
a[i].height = h, a[i].width = w;
}
sort(a, a + 5, cmp3);
cout << "输出数据\n";
for (i = 0; i < 5; i++)
{
cout << a[i].width << " ";
}
cout << "\n";
return 0;
}
运行结果:
请输入数据
5 10
3 2
6 7
8 4
12 8
输出数据
8 4 7 10 2