Heap storage rules

If the elements of a set can be compared with total order semantics then these elements can be stored in a heap. A heap is a binary tree in which these two rules are followed:

To implement a priority queue is easy using heaps since:

The element contained by each node has a priority that is greater than or equal to the priorities of the elements of that node’s children.

The tree is a complete binary tree

Adding an element to a heap

Add always at the bottom in the last position open.

Removing an element from the heap

  1. The element that we will be removing will always be the root. To do so, save the value of the root into a variable.
  2. Copy the last element in the deepest level to the root This will be called the out-of-place element.
  3. Take this last node out of the tree.
  4. While the out-of-place element has a priority that is lower than the one of its children) Swap the out of place element with its highest priority child.
  5. Return the value that you saved in step 1.