1265 蓝桥杯 排序 简单

1265 蓝桥杯 排序 简单

cpp 复制代码
//C++风格解法1,sort正序排序,正、逆序分别输出,通过率100%
#include <bits/stdc++.h>
using namespace std;

const int N = 5e5 + 10;
int a[N];

int main(){
  int n;cin >> n;
  for(int i = 1; i <= n; ++i)cin >> a[i];

  sort(a + 1, a + 1 + n);    //快速排序平均时间复杂度O(nlogn),范围左闭右开

  for(int i = 1; i <= n; ++i)cout << a[i] << " \n"[i == n]; 
  //" \n"[i == n] i != n时输出空格,否则输出换行符

  for(int i = n; i >= 1; --i)cout << a[i] << " \n"[i == 1];
  // " \n"[i == 1] 判断是否为最后一个元素,是换行,否空格
  return 0;
}
cpp 复制代码
//C++风格解法2,lambda表达式,正序快排,逆序快排,通过率100%
#include <bits/stdc++.h>
using namespace std;

const int N = 5e5 + 10;
int a[N];

int main(){
  int n;cin >> n;
  for(int i = 1; i <= n; ++i)cin >> a[i];

  sort(a + 1, a + 1 + n);

  for(int i = 1; i <= n; ++i)cout << a[i] << " \n"[i == n];
  
  sort(a + 1, a + 1 + n, [](const int &u, const int &v){return u > v;});
  //sort(a + 1, a + 1 + n, cmp) lambda表达式写法
  for(int i = 1; i <= n; ++i)cout << a[i] << " \n"[i == n];
  
  return 0;
}

Lambda表达式可以嵌套使用,ISO C++14支持基于类型推断的泛型lambda表达式:

cpp 复制代码
sort( a, a+n, [](const auto& a,const auto& b){return a>b;} );//降序排序:不依赖a和b的具体类型

|-----------|-----------|
| 捕捉形式:[] | 不捕获任何外部变量 |

auto:变量的自动类型推断

cpp 复制代码
//C++风格解法3,自定义函数编写排序规则,通过率100%
#include <bits/stdc++.h>
using namespace std;

const int N = 5e5 + 10;
int a[N];

bool cmp(const int &u, const int &v){return u > v;}    
//函数体写在{}里,自定义函数编写排序规则

int main(){
  int n;cin >> n;
  for(int i = 1; i <= n; ++i)cin >> a[i];

  sort(a + 1, a + 1 + n);

  for(int i = 1; i <= n; ++i)cout << a[i] << " ";
  cout << "\n";
  
  sort(a + 1, a + 1 + n,cmp);

  for(int i = 1; i <= n; ++i)cout << a[i] << " \n"[i == n];
  
  return 0;
}

reference:

sort入门_sort(a+1,a+n+1)-CSDN博客

八大排序算法的稳定性和事件复杂度 - tuna- - 博客园 (cnblogs.com)

c++中cout << a[i] << " \n"[i == n - 1];该怎么解释 - CSDN文库

cout <<"\n"[i == n- 1];是如何工作的?-腾讯云开发者社区-腾讯云 (tencent.com)

lambda 表达式------匿名函数 auto i= [ ] () { };_lamda表达式auto-CSDN博客
C++14 Overview, C++ FAQ (isocpp.org)
C++ auto用法及应用详解_c++ auto&-CSDN博客

函数 - C 语言教程 - 网道 (wangdoc.com)

c++应用sort函数时的cmp函数怎么写_c语言中cmp-CSDN博客

相关推荐
是小胡嘛21 小时前
C++之Any类的模拟实现
linux·开发语言·c++
Want5951 天前
C/C++跳动的爱心①
c语言·开发语言·c++
lingggggaaaa1 天前
免杀对抗——C2远控篇&C&C++&DLL注入&过内存核晶&镂空新增&白加黑链&签名程序劫持
c语言·c++·学习·安全·网络安全·免杀对抗
phdsky1 天前
【设计模式】建造者模式
c++·设计模式·建造者模式
H_-H1 天前
关于const应用与const中的c++陷阱
c++
coderxiaohan1 天前
【C++】多态
开发语言·c++
gfdhy1 天前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
百***06011 天前
SpringMVC 请求参数接收
前端·javascript·算法
weixin_457760001 天前
Python 数据结构
数据结构·windows·python
ceclar1231 天前
C++范围操作(2)
开发语言·c++