当前位置:网站首页>归并排序思路及例题
归并排序思路及例题
2022-07-21 12:26:00 【AC-PEACE】
题目
给定你一个长度为 n 的整数数列。
请你使用归并排序对这个数列按照从小到大进行排序。
并将排好序的数列按顺序输出。
输入格式
输入共两行,第一行包含整数 n。
第二行包含 n 个整数(所有整数均在 1∼10^9 范围内),表示整个数列。
输出格式
输出共一行,包含 n 个整数,表示排好序的数列。
数据范围
1≤n≤100000
输入样例:
5 3 1 2 4 5
输出样例:
1 2 3 4 5
代码及思想:
#include<iostream>
using namespace std;
const int N = 100010;
int q[N], tmp[N];
void merge_sort(int q[], int l, int r)
{
if(l >= r) return;//递归的终止情况
//第一步:找到分界点,分成子问题
int mid = l + r >> 1;
//第二步:递归处理子问题
merge_sort(q, l, mid); merge_sort(q, mid + 1, r);
//第三步:*合并子问题*
int k = 0, i = l, j = mid + 1;//k统计tmp数组中排序到了第几个数
while(i <= mid && j <= r)//归并排序是稳定排序,先排i后排j
if(q[i] <= q[j]) tmp[k ++] = q[i ++];
else tmp[k ++] = q[j ++];
while(i <= mid) tmp[k ++] = q[i ++];
while(j <= r) tmp[k ++] = q[j ++];//两个子区间长出来的接到后面
for(i = l, j = 0; i < r; i ++, j ++) q[i] = tmp[j];
}
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i ++) scanf("%d", &q[i]);
merge_sort(q, 0, n - 1);
for(int i = 0; i < n; i ++) printf("%d ", q[i]);
return 0;
}
边栏推荐
- 单利模式的四种方式
- When the mouse clicks anywhere on the web page, the cursor flashes and the input state is displayed
- 微信小程序反编译研究
- 专访SPORTFIVE李莹:如何用Web3的方式推动体育IP拓展“新商业版图”
- redis学习笔记分享
- SDL2 简明教程(一):使用 Cmake 和 Conan 构建 SDL2 编程环境
- . Replacewith() can only work once
- 打印机漏洞(rce)
- Implement printf function by yourself (serial port printing)
- A simple exploration of Suricata
猜你喜欢
人类月球日 | 专访邹海洋:中国的航天梦,是信任与不辜负的故事
学界VS工业界:深度学习究竟能不能打破视频编解码天花板
Step by step introduction to the development framework based on sqlsugar (12) -- split the content of the page module into components to realize the division and rule processing
Welcome to the CSDN markdown editor template
继承,重写,重载
专访SPORTFIVE李莹:如何用Web3的方式推动体育IP拓展“新商业版图”
交互式虚拟现实技术在药物发现中的新兴潜力
Interview must ask: from entering URL to page display, what happened? (detailed and easy to understand, organized and easy to remember)
Sdl2 concise tutorial (III): display pictures
巴比特 | 元宇宙每日必读:要求高级政府官员披露其在NFT上的所有投资?美国政府道德办公室发布的这份法律咨询还说了什么?...
随机推荐
HCIP笔记整理 2022/7/14
Nacos相关概念小总结
模板继承与导入
日期函数格式转换
When the neural network model is not as good as the decision tree
Sdl2 concise tutorial (2): create an empty window
吴恩达撰文:如何建立适应AI职业生涯的项目
A simple exploration of Suricata
C语言学生成绩管理系统
基于SqlSugar的开发框架循序渐进介绍(12)-- 拆分页面模块内容为组件,实现分而治之的处理
How to use the download tool proayee down
Go语言 接口与类型
【modbus开发】入门教学与协议简介
Printer vulnerability (RCE)
Flex layout example
交互式虚拟现实技术在药物发现中的新兴潜力
嵌套交叉验证
JS how to control the position of the scroll bar of the whole page
第十一节 缓存雪崩、热点数据失效 跟着大宇学Redis--------目录帖
BIB | Mol2Context-vec: 上下文感知的深度网络模型学习分子表示用于药物发现