Heap Sort visualization

Build a max-heap, then repeatedly move the root (maximum) to the end and re-heapify.

The array is viewed as a complete binary tree: children of i live at 2i+1 and 2i+2. A max-heap keeps every parent ≥ its children, so the maximum sits at the root.

Swap the root with the last heap element, shrink the heap, and sift the new root down. Repeat n times — guaranteed O(n log n), in place.

Complexity

Time: best O(n log n), average O(n log n), worst O(n log n). Space: O(1). Difficulty: Advanced.

Pseudocode

procedure heapSort(A):
  for i ← n/2−1 down to 0: siftDown(A, i, n)
  for end ← n−1 down to 1:
    swap(A[0], A[end]); siftDown(A, 0, end)
procedure siftDown(A, i, size):
  largest ← max of i, 2i+1, 2i+2 (within size)
  if largest ≠ i:
    swap(A[i], A[largest]); siftDown(A, largest, size)

More sorting algorithms