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:
- The element contained by each node is greater than or equal to the elements of that node’s children.
- The tee is a complete binary tree so that every level except the deepest must contain as many nodes as possible; at the deepest level all the nodes are as far left as possible.
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.
- Place the new element in the heap in the first available location. This keeps the structure as a complete binary tree, but it might no longer be a heap since the new element might have a higher priority than its parent.
- While (the new element has a priority that is higher than its parent) swap the element with its parent.
Removing an element from the heap
- The element that we will be removing will always be the root. To do so, save the value of the root into a variable.
- Copy the last element in the deepest level to the root This will be called the out-of-place element.
- Take this last node out of the tree.
- 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.
- Return the value that you saved in step 1.