C++ sort函数的使用(时间复杂度为n*log2(n))

调用函数时要有首地址,尾地址,若想表示从大到小或从小到大可以加第三个比较函数,如不,则默认从小到大。
代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int a, int b)
{
	return a > b;//若想从小到大也可以写成return a<b;
}
int main()
{
	int a[10] = { 9, 6, 3, 8, 5, 2, 7, 4, 1, 0 };
	sort(a, a + 10, cmp);//从大到小;
	for (int i = 0; i<10; i++)
		cout << a[i] << endl;
	sort(a, a + 10);//没有第三个参数实现从小到大;
	for (int i = 0; i<10; i++)
		cout << a[i] << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44017102/article/details/88406857