数据结构学习——大根堆

大根堆就是其中每个节点的值都大于或等于其子节点。
大根堆既是大根树又是完全二叉树。
像下图这样:
在这里插入图片描述
大根堆的类中的数据成员是,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;
}
发布了32 篇原创文章 · 获赞 12 · 访问量 1363

猜你喜欢

转载自blog.csdn.net/qq_18873031/article/details/103645478