Ready, Set, Heapify!
A binary heap is a binary tree that
(1) Is complete - new elements must be added at the deepest level from left to right, resulting in a tree with minimal height (i.e. a height of logn where n is the number of nodes)
(2) Satisfies the heap property - for a given node, its ordering relative to its parent (greater than / less than) is maintained across the heap.
In a min heap (example above; source: http://www.algolist.net), therefore, all children are greater than their parent node, and in a max heap all children are less than their parent node.
A heap is full when every non-terminal node has two children.
Heaps are one concrete implementation of a priority queue, an abstract data structure in which each element has a priority relative to others and elements with higher priority are served before those with lower priority (and those with equal priority are served in the order they appear in the queue).
We can represent/implement a heap as an array, where the root node is the first element, followed by its children from left to right, and so on. Because the heap is a complete binary tree, each parent has exactly 2 children (except for the last one, which could have 0, 1 or 2), so there's a formula for indexing into the array and getting an element's parent or children:
parent_idx = floor((child_idx - 1) / 2) child_indices = 2*(parent_idx + 1), 2*(parent_idx + 2)
Indexing into an array is constant so this gives us O(1) lookup of children/parents.
Public API of a heap:
#peek (#peek_min / #peek_max)
#extract (#extract_min / #extract_max)
#insert / #push
Peek is O(1): you're just looking up the value of your root node, which will always be the first element in the array representing the heap.
Extraction is O(logn): to extract an element, we swap it with the element in the tail position and then heapify down accordingly, which in the worst case requires making as many swaps as their are levels in the tree (logn).
Insertion is O(logn) for the same reason - we insert the element into the tail position and heapify up until the heap property is satisfied, which could take up to logn swaps.














