Data structure learning - large root heap

Wherein the stack is large root value for each node is equal to or greater than its child nodes.
Large root heap is both a large tree root is complete binary tree.
Such as the FIG:
Here Insert Picture Description
large root heap data members that (a type of one-dimensional array T) heap array, arrayLength (the capacity of the heap array), heapSize (number of elements in the stack)

The following is a stack of large root insert functions:

//插入函数
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;
}

Delete function:

//删除函数
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;
}
Published 32 original articles · won praise 12 · views 1363

Guess you like

Origin blog.csdn.net/qq_18873031/article/details/103645478