JMU
Heaps
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
An Example

A 3-Heap

images/3heap.gif
Creating and Maintaining a Heap
The "Sift Up" Process
    siftup(i)
    {
        while (i is not the root node and i.value > i.parent.value) {

            swap(i, i.parent);
        }
    }
    

Suppose a node with value 44 is added to the end of the 3-heap above...

images/3heap_siftup.gif
The "Sift Down" Process
    siftdown(i)
    {
        while (i is not a leaf node and i.value < i.maxchild.value) {

            swap(i, i.maxchild);
        }
    }
    

Suppose the value of the root node is changed to 43...

images/3heap_siftdown.gif
Adding and Removing Nodes
    add(i)
    {
        add i to the back of the heap;

        siftup(i);
    }
    
    remove()
    {
        swap(front, back);

        remove the back element;

        siftdown(front);
    }
    
Time Efficiency Bounds