当前位置:网站首页>快速排序例题
快速排序例题
2022-07-13 18:13:00 【AC-PEACE】
题目:
给定你一个长度为 n 的整数数列。
请你使用快速排序对这个数列按照从小到大进行排序。
并将排好序的数列按顺序输出。
输入格式
输入共两行,第一行包含整数 n。
第二行包含 n 个整数(所有整数均在 1∼10^9 范围内),表示整个数列。
输出格式
输出共一行,包含 n 个整数,表示排好序的数列。
数据范围
1≤n≤100000
输入样例:
5
3 1 2 4 5
输出样例:
1 2 3 4 5思路 :
快排属于分治算法,分治算法一般分为三步:
1. 分成子问题
2. 递归处理子问题
3. 子问题合并
void quick_sort(int q[], int l, int r)
{
if(l >= r) return;//递归的终止条件
//第一步:分成子问题
int i = l - 1, j = r + 1, x = q[l + r >> 1];
while(i < j)
{
do i++; while(q[i] < x);//令 q[l..i-1] <= x, q[i] >= x
do j--; while(q[j] > x);//令 q[j+1..r] >= x, q[j] <= x
if(i < j) swap(q[i], q[j]);//令 q[l..i] <= x, q[j..r] >= x
} //while循环结束后,q[l..j] <= x,q[j+1..r] >= x
//第二步:递归处理子问题
quick_sort(q, l, j);
quick_sort(q, j + 1, r);
//第三步:子问题合并.快排这一步不需要操作,但归并排序的核心在这一步骤
}代码段:
#include<iostream>
using namespace std;
const int N = 100010;
int q[N];
void quick_sort(int q[], int l, int r)
{
if(l >= r) return;
int i = l - 1, j = r + 1;
int x = q[l + r >> 1];
while(i < j)
{
do i ++; while(q[i] < x);
do j --; while(q[j] > x);
if(i < j) swap(q[i], q[j]);
}
quick_sort(q, l, j);
quick_sort(q, j + 1, r);
}
int main()
{
int n;
scanf("%d", &n);
for(int i = 0; i < n; i ++) scanf("%d", &q[i]);
quick_sort(q, 0, n - 1);
for(int i = 0; i < n; i ++) printf("%d ", q[i]);
return 0;
}
边栏推荐
- Prism publish subscription
- 小程序毕设作品之微信企业公司小程序毕业设计(2)小程序功能
- 微信小程序开发—(八)canvas绘制图形
- Dart中的库
- Im2col+pack+sgemm optimized for AI mobile terminal
- Libraries in dart
- C primer plus学习笔记 —— 4、文件IO(输入/输出)
- Rasa Action Service concurrency
- 小程序毕设作品之微信企业公司小程序毕业设计(7)中期检查报告
- Xiao Bai can understand tacotron's Chinese speech synthesis practice
猜你喜欢
随机推荐
Analysis of local anti debugging principle of sojson
Axelar: what is moonbeam? What can be built on moonbeam?
使用cpolar建立一个商业网站(申请网站安全证书)
Simple canvas animation principle
记一次UI自动化导致APP未响应问题
微信小程序开发—(五)弹出框
Execute methods or events after loading the interface in MVVM
手机自动化使用命令查看APP包名
将 Terraform 生态粘合到 Kubernetes 世界
自动化测试工具-Playwright(快速上手)
EasyCVR接入国标设备后,设备录像不能完整播放该如何解决?
JMeter 常用的几种断言方法,你会了吗?
Design simulation of smart home monitoring system based on 51 single chip microcomputer (proteus simulation + source code + Report)
分账系统如何给连锁便利店带来交易效率革命?
51单片机智能家居环境检测 烟雾温度GSM短信提示报警器(原理图+程序+仿真+PCB)
小程序毕设作品之微信企业公司小程序毕业设计(6)开题答辩PPT
使用PyQt5 初始化时,super() 和 _ init _ () 函数的配合使用所面临的问题,以及对应的学习和解决方案
Personnel management system C language version
. Net core web API using log4net logs
Kubernetes Dashboard

![LeetCode 735 行星碰撞[栈 模拟] HERODING的LeetCode之路](/img/cb/fe68c558b526555cfa6992233407fe.png)







