flowchart TB A(1: A) --- B(2: B) A --- C(3: C) B --- D(4: D) B --- E(5: E) C --- F(6: F) C --- G(7: G)
Binary Heap
For better priority queuing
Check out a video by Abdul Bari.
Represent a binary tree in an array
To represent a binary tree in an array, you can follow these rules:
- If the root of the tree is at index
1<- easier to remember - For a node at index \(i\):
- The left child is at index \(2i\).
- The right child is at index \(2i+1\).
- The parent is at index \(\lfloor \frac{i}{2} \rfloor\).
- If the root of the tree is at index
0<- when implementing - For a node at index \(i\):
- The left child is at index \(2i+1\).
- The right child is at index \(2i+2\).
- The parent is at index \(\lfloor \frac{i - 1}{2} \rfloor\).
The definition of an (almost) complete binary tree becomes clearer when we represent tree structure as an array. We should not allow any null values between the elements.
Now you may be thinking about the difference between binary trees and heaps. Actually, while all heaps are binary trees, not all binary trees are heaps. You must fulfill the heap property. So what is it?
Heap property
The heap property dictates the relationship between a parent node and its children in a binary tree. It can be defined in two ways, leading to two different types of heaps:
Min-heap property \[A[\lfloor \frac{i}{2} \rfloor] \leq A[i]\]
Max-heap property \[A[\lfloor \frac{i}{2} \rfloor] \geq A[i]\]
I find defining the property with the relationship of a current node \(i\) and the parent node \(\lfloor \dfrac{i}{2} \rfloor\) is more simple (since it can handle the root condition).
If you have an array \(A\) with no null values between elements, you are already satisfying the almost complete binary tree property and are halfway ready to be a heap structure. How cool is that!
The remaining half of the process is called build-heap. We build-heap by heapifying \(n\) times.
From now on, we will take a close look at the max-heap since the min-heap and max-heap are basically the same.
Heapify
Check out the video by Techdose helps!
flowchart TB A( ) -.- 10 A( ) -.- B( ) 10 --- 8 10 --- 12 8 -.- C( ) 8 -.- D( ) 12 -.- E( ) 12 -.- F( )
Let’s examine the tree above (with node 10 as root). Assert that the subtrees under node 10 are max-heaps. By recursively sifting down (similar to bubble sorting) on node 10, the entire tree will eventually become a max-heap.
The time complexity of heapifying is the same as the height of the heapifying index. Thankfully, the tree is balanced from the very start, which makes it \(O(\log n)\). Obvious, right?
Build heap
Thanks again for the video!
Let’s transform an arbitrary array \(A\) into a heap using the build-heap process.
\[\begin{align*} A &\quad \begin{bmatrix} 2 & 12 & 5 & 15 & 16 & 2 & 6 & 9 & 1 & 4 \end{bmatrix} \\ \text{Build-Max-Heap}(A) &\quad \begin{bmatrix} 16 & 15 & 6 & 9 & 12 & 2 & 5 & 2 & 1 & 4 \end{bmatrix} \end{align*}\]
At first glance, it might seem intuitive that repeatedly heapifying the array \(n\) times, starting from the right (or bottom), will transform \(A\) into a heap.
Would it be surprising to you if I told you that the time complexity of the build-heap algorithm is actually \(O(n)\) instead of \(O(n \log n)\)?
maxheapify.go
// MaxHeap constructs a max-heap from an unordered array
// `i` starts from 0 in this code
// We are basically bubble sorting from node `i` to the leaf node
// while iterating `i` from n to 0.
func BuildMaxHeap(arr []int, n int) {
// Start from the last non-leaf node and heapify each node
1 for i := n/2 - 1; i >= 0; i-- {
MaxHeapify(arr, n, i)
}
}
// MaxHeapify ensures the subtree rooted at index i is a max-heap
// i
// / \
// left right
func MaxHeapify(arr []int, n, i int) {
largest := i // Initialize largest as root
left := 2*i + 1 // left child index
right := 2*i + 2 // right child index
// If left child is larger than root
if left < n && arr[left] > arr[largest] {
largest = left
}
// If right child is larger than the largest so far
if right < n && arr[right] > arr[largest] {
largest = right
}
// If largest is not root
if largest != i {
arr[i], arr[largest] = arr[largest], arr[i] // Swap
// Recursively heapify the affected subtree
MaxHeapify(arr, n, largest)
}
}- 1
-
The
forloop can be iterated fromnto0. However, since half of the elements (which are leaf nodes) are already part of a heap, we can start from the node that is not a leaf.
Level 0 1 Height 3
/ \
Level 1 2 3 Height 2
/ \ / \
Level 2 4 5 6 7 Height 1
/ \ / \ / \ / \
Level 3 8 9 10 11 12 13 14 15 Height 0
Try to imagine a complete binary tree with a large number of levels. Pick any level you desire in between and set it as \(l\).
- The indices of the first elements at each level are \(2^l\) and the level of a certain index is \(\lfloor \log_{2} i \rfloor\).
- There are \(2^{l}-1\) nodes in the whole tree just before level \(l\).
- There are \(2^{l}\) nodes at level \(l\).
- There are \(2^{l+1}\) nodes at the next level, \(l+1\), which is twice as many.
- At height \(h\), there are at most \(\lceil \frac{N}{2^{h+1}} \rceil\) nodes, where \(h\) means the longest downward path from that node to a leaf.
The nodes at height \(h\) needs to be heapified by sifting down \(h\) times and there are \(\lceil \frac{N}{2^{h+1}} \rceil\) nodes max at each height \(h\) which makes,
\[ \begin{align*} \sum_{h=0}^{\lfloor \log_2 N \rfloor} \lceil \dfrac{N}{2^{h+1}} \rceil O(h) &< O \left( \sum_{h=0}^{\infty} \dfrac{N}{2^{h+1}} C h \right) \\ &= O \left( \dfrac{CN}{2} \sum_{h=0}^{\infty} \dfrac{h}{2^{h}} \right) \\ &= O \left( \dfrac{CN}{2} 2 \right) \\ &= O(N) \end{align*} \]
The talor series is useful when explaining this.
The parent of the last element can be considered the last node that is not a leaf node.
\[ A[\lfloor \dfrac{n}{2} \rfloor + 1:n] \]
Congratulations! You now have a beautiful max-heap ready. Let’s utilize this as a priority queue.
Inserting and popping elements in the queue
Insert from the right, pop from the left.
Inserting from the right helps us to maintain the almost complete binary tree property, but the max-heap property is broken.
\[\begin{align*} A_\text{max-heap} &\quad \begin{bmatrix} 16 & 15 & 6 & 9 & 12 & 2 & 5 & 2 & 1 & 4 \end{bmatrix}\\ A_\text{broken-max-heap} &\quad \begin{bmatrix} 16 & 15 & 6 & 9 & 12 & 2 & 5 & 2 & 1 & 4 & 100 \end{bmatrix}\\ &\quad \begin{bmatrix} 16 & 15 & 6 & 9 & 100 & 2 & 5 & 2 & 1 & 4 & 12 \end{bmatrix}\\ &\quad \begin{bmatrix} 16 & 100 & 6 & 9 & 15 & 2 & 5 & 2 & 1 & 4 & 12 \end{bmatrix}\\ A_\text{max-heap} &\quad \begin{bmatrix} 100 & 16 & 6 & 9 & 15 & 2 & 5 & 2 & 1 & 4 & 12 \end{bmatrix}\\ \end{align*}\]
The solution is to check the integrity from the inserted leaf node to the root. Simply compare with the parent node and propagate upward to the top. In the array representation, it seems like hopping to the left for \(\log n\) times.
Popping is done by removing the root and replacing it with the last leaf node. To preserve the max-heap property, we propagate downward from the root to the bottom.
\[\begin{align*} A_\text{max-heap} &\quad \begin{bmatrix} 100 & 16 & 6 & 9 & 15 & 2 & 5 & 2 & 1 & 4 & 12 \end{bmatrix}\\ A_\text{broken-max-heap} &\quad \begin{bmatrix} 12 & 16 & 6 & 9 & 15 & 2 & 5 & 2 & 1 & 4 \end{bmatrix}\\ &\quad \begin{bmatrix} 16 & 12 & 6 & 9 & 15 & 2 & 5 & 2 & 1 & 4 \end{bmatrix}\\ A_\text{max-heap} &\quad \begin{bmatrix} 16 & 15 & 6 & 9 & 12 & 2 & 5 & 2 & 1 & 4 \end{bmatrix}\\ \end{align*}\]
Notice that the root node always holds the maximum value of the entire tree. This characteristic enables sorting; you simply keep popping the root until the heap is empty.
Heap sort
Why do we need to create a dedicated paragraph for sorting when it is so straightforward? There is a fun little idea behind heap sorting in an array that makes it more elegant.
heapsort.go
- 1
- First, create a max-heap.
- 2
- Instead of popping and stacking the elements into a new empty array, we utilize the original array. After popping, there is a spare index because the size of the heap is reduced.
- 3
-
By marking the end of the max-heap with
m, we can swap the root value with the leaf at the very end. The popped value will be stacked from the end of the array, and eventually, the array will become a sorted array in ascending order.