堆排序code

#include<bits/stdc++.h>

using namespace std;

#define maxn 501

int arrmaxn;

void swap(int i,int j){

int tmp=arri;

arri=arrj;

arrj=tmp;

}

//向上调整函数

void heapinsert(int x){

if(x==0) return;

int i=(x-1)/2; //父节点

while(1){

if(i<0||arri>=arrx) break;

else{

swap(x,i);

}

x=i;

i=(i-1)/2;

}

}

//向下调整函数

void heapify(int pl,int size){

int l=pl*2+1;

if(l>=size){

return;

}

while(l<size){

int best=(l+1<size)?(arrl>arrl+1?l:l+1):l;

if(arrbest>arrpl){

swap(best,pl);

}

else{

break;

}

pl=best;

l=pl*2+1;

}

}

//从顶到底建堆排序

void heapsort1(int n){

for(int i=0;i<n;i++){

heapinsert(i);

}

int size=n;

while(size>1){

size--;

swap(0,size);

heapify(0,size);

}

}

//从底到顶建堆排序

void heapsort2(int n){

for(int i=n-1;i>=0;i--){

heapify(i,n);

}

int size=n;

while(size>1){

size--;

swap(0,size);

heapify(0,size);

}

}

void print(int arr\[\],int n){

for(int i=0;i<n;i++){

printf("%d ",arri);

}

puts("");

}

int main(){

int n;

cin>>n;

for(int i=0;i<n;i++){

cin>>arri;

}

//heapsort1(n);

//print(arr,n);

heapsort2(n);

print(arr,n);

return 0;

}

相关推荐
小郎君6582 小时前
Vue keep-alive 切标签后滚动位置回顶?因为 onDeactivated 里读到的 scrollTop 是 0
算法
CodeYp20192 小时前
第15讲:二叉搜索树
开发语言·c++·二叉搜索树
邵奈一2 小时前
GPT-6.1 Terra速度是Sol的3倍,价格减半
算法
RaaS1002 小时前
Node.js Brotli RCE 漏洞自查指南:fetch、undici、axios 都在影响面,三分钟确认你的版本
人工智能·深度学习·算法
shehuiyuelaiyuehao2 小时前
算法56,重排链表
数据结构·算法·链表
pipixia200333 小时前
C++继承面试四连问:内存叠加、私有继承、sizeof、权限重映射
c++·面试·嵌入式·继承·面向对象·对象模型
qq_452396233 小时前
第四篇:《索引原理与实战:B-tree、Hash、GIN、GiST、BRIN》
算法·哈希算法·gin
西索斯coding3 小时前
Qwen3-Max 与 Qwen-Plus:60 个真实修复任务评测方案
大数据·网络·算法·ai
INGNIGHT4 小时前
440 · 背包问题(三)(无限次数)
算法·leetcode·动态规划