sort 函数位于头文件 #include <algorithm> 中,起到排序数组类型的数据结构的作用,对于从小到大排序,sort 函数的默认快排就可以做到:
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int n;
cin >> n;
int a[n];
for (int i = 1;i<=n;i++){
cin >> a[i];
}
sort(a+1,a+n+1);
for (int i = 1;i<=n;i++){
cout << a[i] << " ";
}
return 0;
}
而从大到小怎么排呢?
我们可以写一个副函数来辅助我们:
#include <iostream>
#include <algorithm>
using namespace std;
int larger(int m,int n){
return m > n;
}
int main(){
int n;
cin >> n;
int a[n];
for (int i = 1;i<=n;i++){
cin >> a[i];
}
sort(a+1,a+n+1, larger);
for (int i = 1;i<=n;i++){
cout << a[i] << " ";
}
return 0;
}
我们在sort 函数的默认排序中讲到了sort (a,a+n); 中的 a 是要排序的数组名称,至于从什么排到什么就只用将数组名称看成 0 就能知道了,比如sort (a,a+n);就是从 0 排到 n,而上述的sort(a+1,a+n+1,larger);第三个位置就是表示用什么方式来排序
至于 ? 可以用来代替 if else 来表示判断:
邓紫棋说过:“承认自己不够也是一种勇气!”
诸位道友,多多关照!