To build a MAX heap tree, we can either siftDown
or siftUp
, by sifting down we start from the root and compare it to its two children, then we repl
Actually, building a heap with repeated calls of siftDown
has a complexity of O(n)
whereas building it with repeated calls of siftUp
has a complexity of O(nlogn)
.
This is due to the fact that when you use siftDown
, the time taken by each call decreases with the depth of the node because these nodes are closer to the leaves. When you use siftUp
, the number of swaps increases with the depth of the node because if you are at full depth, you may have to swap all the way to the root. As the number of nodes grows exponentially with the depth of the tree, using siftUp
gives a more expensive algorithm.
Moreover, if you are using a Max-heap to do some sort of sorting where you pop the max element of the heap and then reheapify it, it's easier to do so by using siftDown
. You can reheapify in O(logn)
time by popping the max element, putting the last element at the root node (which was empty because you popped it) and then sifting it down all the way back to its correct spot.