Search code examples
algorithmlanguage-agnosticheapsortmax-heap

Max Heapify-pseudocode


I'm confused on one part of this pseudocode for Max Heap Sort. What does down to 2 mean?

HeapSort(A)
Build-Max-Heap(A)
for i <-- length[A] down to 2
do exchange A[1] <---> A[i]
heap-size[A] =  heap-size[A] -1
Max-Heapify(A,1)

Solution

  • It means that you repeat that block for every value of i in {length[A], length[A] - 1, length[A] - 2, ..., 2}.

    If this were C (or C++, or Java—all the same syntax for this), one could write it:

    for (int i = length(A), i >= 2, i--) {
        do...
    }