c语言实现最大堆关键代码 --自用板子(考试用)

本文分享了C语言实现最大堆的代码,经过测试,功能实现OK。稍加修改即可应用于最小堆。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c语言实现最大堆关键代码 --自用板子(考试用)

代码

下面展示 关键代码

int q[maxn],tot;
int a[maxn];
void insert(int x){
    q[++tot]=x;
    int fa=tot/2;
    int pos=tot;
    while(q[fa]<x){
        q[pos]=q[fa];
        q[fa]=x;
        fa/=2;
        pos/=2;
    }
}
int top(){
    return q[1];
}
void pop(){
    int tmp=q[tot--];
    int fa=1,child;
    for(child=fa*2;child<=tot;child=fa*2){
        if(child+1<=tot&&q[child]<q[child+1])child++;
        if(q[child]>tmp){
            q[fa]=q[child];
            fa=child;
        }else
            break;
    }
    q[fa]=tmp;
}

测试

10
5 4 8 9 7 0 5 123 76 8
123 76 9 8 8 7 5 5 4 0 
Program ended with exit code: 0

效果达到 ok!
最小堆代码微调即可,有空更新

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值