[] Data structure heap of deleted

topic

Delete heap achieve a given minimum number of elements in the pos by x return, delete returns true success, failure returns false. (Note: After deleting the data structure is to maintain the minimum heap.)

Algorithm

The minimum heap deleted after a given number of elements as pos, we can delete the element stack up to the last element of the seat, and then adjust downward as the stack, from the upward adjustment of the position of the heap.
If an empty stack returns to false
2 = X heap [pos]; // return the element
3 heap [pos] = heap [ currentSize - 1]; // last element to fill junction pos
. 4 currentSize--;
. 5 siftDown (pos, currentSize - 1); // adjust the top-down stack
6 siftUp (pos); // stack is adjusted upward
time complexity is O (logn)

Code

template <class E>bool MinHeap <E>::Remove(int &pos,E &x) 
{
    if (!currentSize) { //堆空, 返回false   
        cout << "Heap empty" << endl;
        return false;
    }
    x = heap[pos];      // 返回该元素
    heap[pos] = heap[currentSize - 1];  //最后元素填补到pos结点
    currentSize--;
    siftDown(pos, currentSize - 1);//自上向下调整为堆
    siftUp(pos);
    return true;
}

Guess you like

Origin www.cnblogs.com/muyefeiwu/p/11838600.html