c++ sort函数

  1. sort函数可以三个参数也可以两个参数,必须的头文件#include < algorithm>
  2. 它使用的排序方法是类似于快排的方法,时间复杂度为 n l o g 2 ( n ) nlog_2{(n)} nlog2(n)
  3. Sort函数有三个参数:(第三个参数可不写)
  • 第一个是要排序的数组的起始地址
  • 第二个是结束地址(最后一位要排序的地址),这两者都是地址
  • 第三个参数是排序的方法,可以是从大到小也可是从小到大,还可以不写第三个参数,此时默认的排序方法是从小到大排序。
#include 
#include 
using namespace std;

//比较函数,用来传给第三个参数
int cmp(const int &a, const int &b)
{
	if(a > b)
	{
		return true;
	}
	return false;
}
int main()
{
	int a[20] = {2,4,1,23,-37,5,76,0,43,24,65,-34,-8,77};
	for(int i=0; i<20; i++)
	{
		cout << a[i] << " ";
	}
	cout << endl;
	sort(a, a+20);
	for(int i=0; i<20; i++)
	{
		cout << a[i] << " ";
	}
	cout << endl;

	sort(a, a+20, cmp);
	for(int i=0; i<20; i++)
	{
		cout << a[i] << " ";
	}
	cout << endl;
	return 0;
}

结果如下:

2 4 1 23 -37 5 76 0 43 24 65 -34 -8 77 0 0 0 0 0 0
-37 -34 -8 0 0 0 0 0 0 0 1 2 4 5 23 24 43 65 76 77
77 76 65 43 24 23 5 4 2 1 0 0 0 0 0 0 0 -8 -34 -37

可见默认情况下是升序排序。自己增加了一个比较函数之后就降序排列了。

你可能感兴趣的:(C/CPP)