当前位置:网站首页>堆排序实现代码
堆排序实现代码
2022-08-08 19:00:00 【就一枚小白】
降序
构建最小堆
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
int arr[N];
void adjust(int a[], int n, int i){
int mi = i, l = i * 2 + 1, r = i * 2 + 2;
if(l < n && a[mi] > a[l]) mi = l;
if(r < n && a[mi] > a[r]) mi = r;
if(mi != i){
swap(a[mi], a[i]);
adjust(a, n, mi);
}
}
void buildMinHeap(int a[], int n){
for(int i = n / 2 - 1; i >= 0; i--){
adjust(a, n, i);
}
for(int i = n - 1; i >= 0; i--){
swap(a[0], a[i]);
adjust(a, i, 0);
}
}
int main(){
int n;
cin >> n;
for(int i = 0; i < n; i++) cin >> arr[i];
buildMinHeap(arr, n);
return 0;
}
升序
构建最大堆
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
int arr[N];
void adjust(int a[], int n, int i){
int ma = i, l = i * 2 + 1, r = i * 2 + 2;
if(l < n && a[ma] < a[l]) ma = l;
if(r < n && a[ma] < a[r]) ma = r;
if(ma != i){
swap(a[ma], a[i]);
adjust(a, n, ma);
}
}
void buildMinHeap(int a[], int n){
for(int i = n / 2 - 1; i >= 0; i--){
adjust(a, n, i);
}
for(int i = n - 1; i >= 0; i--){
swap(a[0], a[i]);
adjust(a, i, 0);
}
}
int main(){
int n;
cin >> n;
for(int i = 0; i < n; i++) cin >> arr[i];
buildMinHeap(arr, n);
return 0;
}
边栏推荐
- 分布式文件系统fastDFS
- run fscript with lua
- The origin and creation of Smobiler's complex controls
- This error is reported when the shake database is started. Is there a problem with the configuration?
- 智驾科技完成C1轮融资,此前2轮已融4.5亿元
- Which company is the best for futures account opening? It must be formal and safe
- Shell编程之循环语句与函数
- Implementing Forward+ in Unity URP
- 3D角色建模师和3D角色动画师哪个更有前景?哪个更适合小白入门?
- Redis之SDS数据结构
猜你喜欢
Build DG will increase the amount of lead to archive log problem
APICloud AVM 封装日期和时间选择组件
golang流程控制:if分支、switch分支和fallthrough switch穿透
uniapp父组件使用prop将异步的数据传给子组件
MogDB学习笔记-从0开始
鹅厂机器狗花式穿越10m梅花桩:前空翻、单桩跳、起身作揖...全程不打一个趔趄
OpenSSH生成的私钥如何在putty中使用?
疫情期间闲来无事,我自制了一个按钮展示框特效来展示我的博客
Open Office XML 格式中的 Style 设计原理
PG 之 huge page
随机推荐
架构设计基本原则
蒲公英R300A 4G路由器,远程监控PLC教程
【kali-权限提升】(4.2.6)社会工程学工具包(上):中间人攻击原理
Oracle--表
能力一般,却可以大厂随便横跳?强在哪里?
MogDB study notes - starting from 0
hdu2647 N!Again
LabVIEW报错“仪器IO助手未正确安装”
倒置字符串
Group DETR:分组一对多匹配是加速DETR收敛的关键
请问shake数据库中mongoshake同步过程中,src_mongo挂了,同步服务不会退出吗?
Redhat 7 Maria DB安装与配置
Implement the entire process of Mock API with tools
干货技巧|如何用3DsMax制作笔记本电脑
odoo 登录布局调整
Which company is the best for futures account opening? It must be formal and safe
卡通渲染的历史
【761. Special binary sequence】
01、前言
[极客大挑战 2019]BuyFlag&&[HCTF 2018]admin