Complexity Analysis
We'll cover the following
Building the heap
As mentioned in the previous lesson, the time complexity of building a heap is . This is not obvious right away so let’s analyse the algorithm.
The entire building of the heap can be expressed as heapify events. Each heapify event take time where is the height of the tree.
When I say heapify in this lesson, I mean the top to bottom heapify, the same can be proved for the bottom to up heapify as well.
Each heapify event can be provided with a tighter upper bound than . For example, for leaf nodes, the heapify event is just operation since there is no node below to propagate the heapify to.
Number of operations
Step by step:
- element (root): levels below it, so operations
- For the next two elements to : operations.
- For the next four elements to : operations.
- And so on…
- Second last level: 2 operations.
- Leaf nodes (last level): 1 operation.
For the sake of simplicity, let’s assume is a power of so that we work with a complete binary heap.
Also, recall that the count of nodes at any level can be expressed in terms of . Nodes halves every level as two nodes connects to one node each time to go up a level.
-
Nodes in the last level (leafs) = . Let’s call this level .
-
Nodes in the second last level i.e. level = .
-
Nodes in level 2 =
-
And so on… where the last level, the level has only node, the root.
Compute time per level
List out the number of operations required for each level of the tree rather than each node because the count of operations will be the same for all nodes with the same level.
-
Level : operation for nodes.
-
Level : operations for nodes.
-
Level : operations for nodes.
-
…
-
Level : operations for node.
or,
We can extend the summation to to get the upper bound.
The term can be derived from the sum of infinite GP.
Sum of infinite GP is:
Differentiate both sides
Multiply by
Putting , we get the second term.
Putting this result back into the above equation
In the next lesson, we’ll see how to use the STL priority queue for heap operations.
Get hands-on with 1400+ tech skills courses.