Heap
About
It is a Binary Tree where every child is:
Smaller than the current node. (
Max Heap)Larger than the current node. (
Min Heap)
Heap has a weak ordering, meaning that it is not totally ordered like a BST.
The order is only locally maintained, enough to satisfy the Heap conditions above.
Whenever a node is added or deleted, the Tree MUST be ajusted.
Used in priority queues for example.
Node sequence of Heap
Nodes of the Heap follow a sequence to defines the first and last node of the Tree.
This sequence also helps on insertion and deletion, since inserted elements are added to the end (or last position), and deleted elements are deleted at position 0 (first position).
Inserting an element (Tree)
Elements are added at either:
The last level (height) where you have an empty space. (Usually from left to right)
New created level. (Usually from left to right)
Then check the added element X against AncestorX to see if it satisfy
Heapconditions.Repeat 2. until
Heapconditions are satisfied.
The repeat 2. process is called Heapify Up, where the added node thies to bubble up in the Tree.
Runs on O(logN) since the Tree is always balanced.
Deleting an element (Tree)
The top element is the one deleted.
Then the very last node X in the Tree takes the place of the top node.
The X node is checked against:
In a
MinHeap, the smallest of Xchild, then if Xchild<X they swapp positions.In a
MaxHeap, the highest of Xchild, then if they swapp positions.
Repeat 3. until
Heapconditions are satisfied.
The repeat 3. process is called Heapify Down, where the node that took place of the deleted node tries to bubble down in the Tree.
Runs on O(logN) since the Tree is always balanced.
Implementing Heap with Arrays
Heaps can easily be implemented with Arrays Data Structures, and thus facilitating the removal of nodes.
You simulate left and right childs and parent nodes in Arrays with the following formulas: (where i is the current node index being looked)
left child: 2i+1right child: 2i+2parent node: ⌊2(i−1)⌋
Last updated