当前位置:网站首页>堆排序实现代码
堆排序实现代码
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;
}
边栏推荐
- How to add F4 Value Help to the input parameters of the report in the ABAP report
- vue项目打包后的网页缓存问题
- 制造企业为什么要部署数字化工厂系统
- LabVIEW报错“仪器IO助手未正确安装”
- 大学生图书馆网页设计模板代码 DIV布局书店网页作业成品 学校书籍网页制作模板 学生简单书籍阅读网站设计成品
- PX4-做飞控二次开发需要知道的事情-Cxm
- Implement the entire process of Mock API with tools
- FastDFS distributed file system
- nyoj685 查找字符串(map)
- Learn about layered architecture & SOA architecture together
猜你喜欢
vue项目打包后的网页缓存问题
分布式文件系统fastDFS
制造企业为什么要部署数字化工厂系统
The difference between Redis' memory elimination strategy and expired deletion strategy
Build DG will increase the amount of lead to archive log problem
架构设计基本原则
Fortinet全新云原生保护产品上线亚马逊云科技平台
C语言初阶-结构体
APICloud AVM wraps date and time selection components
堆排序(Heap Sort)实现
随机推荐
蒲公英R300A 4G路由器,远程监控PLC教程
重读GPDB 和 TiDB 论文引发的 HTAP 数据库再思考
ADB安装方法:
Performance optimization | CPU power management from the perspective of ping delay
Which company is the best for futures account opening? It must be formal and safe
[BJDCTF2020]Easy MD5
Transsion Holdings: At present, there is no clear plan for the company's mobile phone products to enter the Chinese market
启牛商学院开户是安全的吗?开户靠谱吗?
The origin and creation of Smobiler's complex controls
Oracle - table
How is the private key generated by OpenSSH used in putty?
企业进行知识共享的好处有哪些?
Redhat 7 Maria DB安装与配置
几何g6将搭载harmonyos系统,产品竞争力全面升级
大学生图书馆网页设计模板代码 DIV布局书店网页作业成品 学校书籍网页制作模板 学生简单书籍阅读网站设计成品
golang流程控制:if分支、switch分支和fallthrough switch穿透
Securities account is better to choose which brokerage platform, which is more safe
LabVIEW报错“仪器IO助手未正确安装”
一起了解分层架构&SOA架构
What is the main purpose of software testing?