数据结构学习——大根堆

大根堆就是其中每个节点的值都大于或等于其子节点。
大根堆既是大根树又是完全二叉树。
像下图这样:
在这里插入图片描述
大根堆的类中的数据成员是,heap数组(一个类型为T的一维数组),arrayLength(数组heap的容量),heapSize(堆的元素个数)

以下是大根堆的插入函数:

//插入函数
template<class T>
void maxHeap<T>::push(const T& theElement)
{
    //若数组长度不够
    if(heapSize==arrayLength-1)
    {
        changeLength1D(heap,arrayLength,2*arrayLength);
        arrayLength*=2;
    }
    int currentNode=++heapSize;
    while(currentNode!=1&&heap[currentNode/2]<theElement)
    {
        heap[currentNode]=heap[currentNode/2];
        currentNode/=2;
    }
    heap[currentNode]=theElement;
}

删除函数:

//删除函数
template<class T>
void maxHeap<T>::pop()
{
    if(heapSize==0)
        throw queueEmpty();//若堆为空
    //删除最大元素
    heap[1].~T();
    //删除最后一个元素,重新建堆
    T lastElement=heap[heapSize--];
    //从根开始,为最后一个元素寻找元素
    int currentNode=1,child=2;
    while(child<=heapSize)
    {
        if(child<heapSize&&heap[child]<heap[child+1])
            child++;
        //可以把lastElement放在heap[currentNode]吗?
        if(lastElement>=heap[child])
            break;
        heap[currentNode]=heap[child];//把孩子child向上移动
        currentNode=child;//向下移动一层寻找位置
        child*=2;
    }
    heap[currentNode]=lastElement;
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值