sort()函数是c++一种排序方法之一,相较冒泡排序和选择排序所带来的执行效率不高的问题,sort()函数使用的排序方法是类似于快速排序的方法,时间复杂度为n*log2 (n),执行效率较高。
直接上代码(这是从大到小),如果想得到从小到大,删掉第4,5行代码和第8行的complare即可,因为sort函数默认从小到大排列。
#include<iostream>
#include<algorithm>
using namespace std;
bool complare(int a,int b)
{return a>b;}
int main(){
int a[10]={0,1,2,3,4,5,6,7,8,9}; sort(a,a+10,complare);
for(int i=0;i<10;i++) cout<<a[i]<<" "; }