# heapify last 3 lines

Last 3 lines of heapify pseudocode are:

if largest =! i
then exchange A[i] and A[largest]
Max_Heapify(A, largest)


What is the aim of the last line? Since largest still holds value of largest leaf, which is now root, what would the recursive run achieve? Just an empty run, it seems.Max-heap is already built.

• We expect references to fulfill the minimal scholarly requirements and be as robust over time as possible. Please take some time to improve your post in this regard. We have collected some advice here.
– Raphael
Mar 16, 2016 at 15:13
• These lines can only be understood in the context of the rest. It does not make much sense to ask about one line in isolation.
– Raphael
Mar 16, 2016 at 15:14
• Part of our mission on this site is to build up a repository of high-quality questions and answers that might be useful to others in the future.
– D.W.
Mar 16, 2016 at 17:31
• Plus, for all we know Yuval has another variant of the algorithm and his answer doesn't fit yours at all, but you are not in the position to notice. (I'd hope that he clicked through to that PDF, but it's generally better not to assume that.)
– Raphael
Mar 17, 2016 at 8:06

You are asking several related questions. I will only answer the first one. The heapify procedure gets an almost-heap $A$ and a node $i$. The heap property is satisfied for all nodes except for $i$. Heapify proceeds as follows:
1. Determine the largest child $j$ of $i$.
2. If $A[i] \geq A[j]$, the heap property is already satisfied.
3. Otherwise, exchange $A[i]$ and $A[j]$, and run heapify on $A$ and $j$.
After the exchange, the heap property is no longer violated for $i$, but might be violated for $j$. For this reason we have to call heapify recursively on the node $j$.