Question: Why do we want the loop index i
in line 2 of BUILD-MAX-HEAP to decrease from ⌊length[A]/2⌋
to 1
rather than increase from 1
to ⌊length[A]/2⌋
?
Algorithms: (Courtesy Introduction to Algorithms book):
I tried to show this using drawings as follows.
Approach 1: if we apply build heap the opposite way from 1
to ⌊length[A]/2⌋
of array A = <5,3,17,10,84>
, we would have:
Approach 2: if we apply build heap the opposite way from ⌊length[A]/2⌋
and decrease to 1
of array A = <5,3,17,10,84>
, we would have:
Problem: I see that in both cases the heap property that parent is larger than its children is maintained, so I don't see why a solution says that there would be a problem such that, "we won't be allowed to call MAX-HEAPIFY, since it will fail the condition of having the subtrees be max-heaps. That is, if we start with 1
, there is no guarantee that A[2]
and A[3]
are roots of max-heaps."