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 = ...