Related Notes: Heap - CS2400
Heap: Complete binary tree whose nodes contain comparable objects.
Caveat: Do not confuse this with dynamic memory; we are talking about the heap ADT.
Two Types of Heaps:
Example: Maxheap Interface
public interface MaxHeapInterface<T extends Comparable<? super T>> { void add (T newEntry); removeMax(); T getMax(); T boolean isEmpty(); int getSize(); void clear(); }
T getMax()
is really justT getRootData()
from theTreeInterface
Priority Queue / FIFO Behavior:
- Suppose you put in the same node (a) twice: a_1 followed by a_2. When you “dequeue”, a_1 will come out first.
We can use a (partially-filled) array to represent a complete binary tree
How-To:
Node n(index)
- Parent: n/2
- Left: 2n
- Right: 2n+1
Note: Inserting
Steps:
- Insert the new value in a way to keeps the tree complete
- Check the parent’s value. Swap the parent and new node if they don’t follow max/min rules.
- Repeat step 2 on the parent node, until you reach the root. (Reheap)
- To insert, you need to be able to find the parent of any node.
Note: Removal
Note: Reheaping the Whole Tree
- Look at the root node and swap it with the smallest/biggest appropriate child to maintain min/max heap.
- Traverse down the tree
Note: Removal
Steps
- Move last node to the position of the node to remove.
- Reheap the whole tree.
Growing the Array:
- You can safely expand the array (copy-by-value to a bigger array). You don’t need to perform any special operations.