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 << ai << " \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博客

相关推荐
郝学胜-神的一滴2 小时前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio
CoderYanger2 小时前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法
Lucas. Wáng4 小时前
Qt学习之旅
c++·qt
星恒随风5 小时前
从0实现C++ AI大模型接入SDK(二):AI知识科普——从图灵测试到ChatGPT,人工智能的发展历程
linux·c++·人工智能·笔记·chatgpt
青少儿编程课堂5 小时前
蓝桥杯真题解析:三维偏序的CDQ分治(全国青少年信息素养大赛与电子学会编程考级)
c++·python·算法·bfs·信息学竞赛
Navigator_Z5 小时前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
geovindu5 小时前
python:Lasso
开发语言·后端·python·算法
AAA修煤气灶刘哥6 小时前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
csdn_aspnet6 小时前
C++ 求给定点集的简单闭合路径(Find Simple Closed Path for a given set of points)
c++
艾莉丝努力练剑6 小时前
【AI接入大模型SDK】解决接口连接异常问题
前端·c++·人工智能·学习·ai·架构