Heap Sort Animation & Pseudocode Walkthrough
Heap sort leverages the structure of a binary heap to continually surface the largest element. The array is first rearranged into a max heap, ensuring every parent is greater than its children. We then repeatedly swap the root with the last unsorted item, shrink the heap, and sift the new root down to restore the heap property. Follow the pseudocode highlights, explanations, and animation to see how the array becomes sorted.
Pseudocode
- for index from ⌊n/2⌋ - 1 down to 0:
- call siftDown(array, index, n - 1)
- for end from n - 1 down to 1:
- swap array[0] with array[end]
- call siftDown(array, 0, end - 1)
- function siftDown(array, root, end):
- while root * 2 + 1 ≤ end:
- let child = root * 2 + 1
- let swapIndex = root
- if array[swapIndex] < array[child]:
- set swapIndex = child
- if child + 1 ≤ end and array[swapIndex] < array[child + 1]:
- set swapIndex = child + 1
- if swapIndex == root: return
- swap array[root] with array[swapIndex]
- set root = swapIndex
Array Animation
comparing
swapping
sorted
Press Play or Step Forward to begin.