题目
法1 sort升序排序,再逆序输出
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 5e5+3;//注意const,全局
int a[N];
int main()
{
//错误int N=5e5+3;
//错误const int a[N];
int n;
cin >> n;
for (int i = 1; i <= n; ++i)cin >> a[i];
sort(a + 1, a + n + 1);//从a[1]开始输入,故从a[1]开始排序
for (int i = 1; i <= n; ++i)cout<< a[i]<<" \n"[i==n];
//逆序输出
for (int i = n; i >= 1; --i)cout << a[i] << " \n"[i == 1];
return 0;
}
“ \n”[i==n] i=n时回车,其余空格
“ \n”[i==1] i=1时回车,其余空格
法2 写一个降序cmp函数
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 5e5+3;//注意const,全局
int a[N];
bool cmp(const int& u, const int& v)
{
return u > v;
}
int main()
{
//错误int N=5e5+3;
//错误const int a[N];
int n;
cin >> n;
for (int i = 1; i <= n; ++i)cin >> a[i];
sort(a + 1, a + n + 1);//从a[1]开始输入,故从a[1]开始排序
for (int i = 1; i <= n; ++i)cout<< a[i]<<" \n"[i==n];
sort(a + 1, a + n + 1,cmp);
for (int i = 1; i <= n; ++i)cout << a[i] << " \n"[i == n];
return 0;
}