排序(快速排序)
难度: 困难 标签: 快速排序
题目描述
给定一个长度为N的数组A,请你先从小到大输出它的每个元素,再从大到小输出它的每个元素。
输入描述
第一行包含一个整数N。
第二行包含N个整数a1,...,an,表示数组A的元素。
1≤N≤5×10^5,−10^9≤ai≤10^9。
输出描述
输出共两行,每行包含N个整数,表示答案。
输入输出样例
示例 1
输入
5
1 3 2 6 5
输出
1 2 3 5 6
6 5 3 2 1
运行限制
最大运行时间:3s
最大运行内存: 128M
重点知识点笔记:
编译语言:C++(g++17)
代码答案:
方法一:
利用正向输出与反向输出实现元素从小到大与从大到小的输出。
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 3;
int a[N];
int main()
{
int n;
scanf("%d", &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] << " \n"[i==n]; //当i=n时输出回车"\n",不然输出空格
for(int i = n; i >= 1; --i) cout << a[i] << " \n"[i==1]; //反向输出
return 0;
}
方法二:
利用自定义比较函数实现元素的从大到小输出(写法①)。
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 3;
int a[N];
int main()
{
int n;
scanf("%d", &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] << " \n"[i==n]; //当i=n时输出回车"\n",不然输出空格
sort(a+1, a+n+1, [](const int &u, const int &v)
{
return u > v; //降序排序
});
for(int i = 1; i <= n; ++i) cout << a[i] << " \n"[i==n]; //当i=n时输出回车"\n",不然输出空格
return 0;
}
方法三:
利用自定义比较函数实现元素的从大到小输出(写法②)。
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 3;
int a[N];
bool cmp(const int &u, const int &v)
{//自定义函数
return u > v; //降序排序
}
int main()
{
int n;
scanf("%d", &n);
int a[n];
for(int i = 1; i <= n; i++)
{
cin >> a[i];
}
sort(a+1, a+n+1); //调用sort()函数,默认升序排序
for(int i = 1; i <= n; i++)
{
cout << a[i] << " ";
}
printf("\n");
sort(a+1, a+n+1, cmp); //调用自定义函数cmp(),降序排序
for(int i = 1; i <= n; i++)
{
cout << a[i] << " ";
}
printf("\n");
return 0;
}