用数组模拟堆——手写大根堆、小根堆模板

了解什么是堆?
小根堆排序模板

大根堆排序

实现的五个基本功能:

  1. 插入一个数:heap[++sz]=x; up(sz); 尾部插入
  2. 求集合中的最大值:heap[1]
  3. 删除最大值:heap[1]=heap[sz]; sz– – ; down(1); 尾部代替头部
  4. 删除任一个结点为k的元素:heap[k]=heap[sz]; sz– – ; down(k); up(k);
  5. 修改任一个结点为k的元素:heap[k]=x; down(k); up(k);

还有一个初始化功能,可直接依靠down函数

#include <iostream>

using namespace std;

const int N=1e5+10;
int heap[N],sz;
//编号从1开始,因此也从下标1开始存数

void down(int x)//结点编号为x,功能,选择父结点x,左孩子x*2,右孩子x*2+1 中最大的作为父结点
{
    int t=x;
    if (x*2<=sz && heap[t]<heap[x*2]) t=x*2;
    if (x*2+1<=sz && heap[t]<heap[x*2+1]) t=x*2+1;
    if (x!=t) {
        swap(heap[t],heap[x]);
        down(t);
    }
}

void up(int x)//判断当前节点x是否大于父结点x/2,是则换
{
    while (x/2 && heap[x] > heap[x/2]) {
        swap(heap[x/2],heap[x]);
        x/=2;
    }
}

void del_x(int x)  //删除结点为x的结点,包括头结点在内
{
    heap[x]=heap[sz--];
    down(x);
    up(x);  //down和up其中只会执行一个。
}

void rep_x(int x,int num)  //替换结点为x的结点的值,包括头结点在内
{
    heap[x]=num;
    down(x);
    up(x);
}

int main() {
    int n;
    scanf("%d",&n);
    for (int i = 1; i <= n; ++i)    scanf("%d",heap+i);
    sz=n;
    for (int i = n/2; i >= 1; --i)  down(i);
    while (n--){
        cout<<heap[1]<<" ";
        del_x(1);
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值