Exercise 6.2-5

The code for MAX-HEAPIFY is quite efficient in terms of constant factors, except possibly for the recursive call in line 10, which might cause some compilers to produce ineficient code. Write an efficient MAX-HEAPIFY that uses an iterative control construct (a loop) instead of recursion.

NEW-MAX-HEAPIFY(A, i)

1  while true:

2  L = LEFT(i)

3  R = RIGHT(i)

4  if L ≤ A.heap-size and A[L] > A[i]:

5      largest = L

6  else largest = i

7  if R ≤ A.heap-size and A[R] < A[i]:

8      largest = R

9  if largest == i:

10     return

11 else:

12     exchange A[i] with A[largest]

13     i = largest