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 replace it with the larger element of the two children, if both children are smaller then we stop, otherwise we continue sifting that element down until we reach a leaf node (or of course again, until that element is larger that both of its children).
Now we will only need to do that n/2
times, because the number of leaves is n/2
, and the leaves will satisfy the heap property when we finish heapifying the last element on the level before the last (before the leaves) - so we will be left with n/2
elements to heapify.
Now if we use siftUp
, we will start with the leaves, and eventually we will need to heapify all n
elements.
My question is: when we use siftDown
, aren't we basically doing two comparisons (comparing the element to its both children), instead of only one comparison when using siftUp
, since we only compare that element to its one parent? If yes, wouldn't that mean that we're doubling the complexity and really ending up with the same exact complexity as sifting down?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…