蓝桥杯省赛无忧 竞赛常用库函数 课件5 排序

01 sort简介

02 sort的用法

cpp 复制代码
sort(起始地址,结束地址的下一位,比较函数);默认用小于号
cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
int main(){
	int a[1000];
	int n;
	//读取数组大小
	cin>>n;
	//读取元素
	for(int i=1;i<=n;i++)cin>>a[i];
	//对数组进行排序 
	sort(a+1,a+n+1);//[1,n+1)左闭右开;a+1指a[1],a+n+1指a[n] 
	//输出
	for(int i=1;i<=n;i++)cout<<a[i]<<' ';
	return 0; 
}
cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
int main(){
	//初始化v
	vector<int> v={5,1,3,9,11};
	//对数组进行排序
	sort(v.begin(),v.end());
	//输出
	for(int i=0;i<v.size();i++) cout<<v[i]<<' ';
}

03 自定义比较函数



04 例题讲解

https://www.lanqiao.cn/problems/1265/learning/?page=1\&first_category_id=1\&problem_id=1265

输入

cpp 复制代码
5
1 3 2 6 5

输出

cpp 复制代码
1 2 3 5 6
6 5 3 2 1
cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
const int N=1e6+3;
int main()
{
  int a[N];
  int n;
  cin>>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]<<' ';
  cout<<endl;
  for(int i=n;i>=1;i--)cout<<a[i]<<' ';
  return 0;
}
相关推荐
兵哥工控1 天前
mfc高精度定时器精简版实例
c++·mfc
爱学大树锯1 天前
1361 · 文字并排
算法
Tisfy1 天前
LeetCode 2483.商店的最少代价:两次遍历 -> 一次遍历
算法·leetcode·题解·遍历
集芯微电科技有限公司1 天前
DC-DC|40V/10A大电流高效率升压恒压控制器
c语言·数据结构·单片机·嵌入式硬件·fpga开发
YGGP1 天前
【Golang】LeetCode 279. 完全平方数
算法·leetcode
小麦嵌入式1 天前
Linux驱动开发实战(十三):RGB LED驱动并发控制——自旋锁与信号量对比详解
linux·c语言·驱动开发·stm32·单片机·嵌入式硬件·物联网
im_AMBER1 天前
Leetcode 87 等价多米诺骨牌对的数量
数据结构·笔记·学习·算法·leetcode
import_random1 天前
[算法]时间序列(介绍)
算法
wuk9981 天前
MATLAB中求解和分析马蒂厄方程
人工智能·算法·matlab
Wang201220131 天前
LSTM和Transformer对比
人工智能·算法·架构