5

Configure inputs and press Visualize to begin.

64
34
25
12
22
11
90
45
Default
Comparing
Swap
Pivot
Sorted
Found
Pseudocode & Implementations
1 approach

Build a max-heap in O(n), then repeatedly extract the maximum and place it at the end. Guaranteed O(n log n) with O(1) space.

HEAP-SORT(A):
  n = length(A)

  // Phase 1: Build max-heap (bottom-up)
  FOR i = floor(n/2)-1 DOWNTO 0:
    HEAPIFY(A, n, i)

  // Phase 2: Extract elements one by one
  FOR i = n-1 DOWNTO 1:
    SWAP(A[0], A[i])     // move max to end
    HEAPIFY(A, i, 0)     // restore heap on reduced array

HEAPIFY(A, size, root):
  largest = root
  left  = 2*root + 1
  right = 2*root + 2

  IF left < size AND A[left] > A[largest]:
    largest = left
  IF right < size AND A[right] > A[largest]:
    largest = right

  IF largest != root:
    SWAP(A[root], A[largest])
    HEAPIFY(A, size, largest)  // fix subtree
Complexity Analysis

Time Complexity

Best Case
LinearithmicO(n log n)
Average
LinearithmicO(n log n)
Worst Case
LinearithmicO(n log n)
Space (aux)
ConstantO(1)
UnstableIn-placeheapguaranteedin-place
About

Builds a max-heap, then repeatedly extracts the maximum element. Combines the best properties of selection sort and merge sort.

Key Insight

O(1) space and O(n log n) time in all cases, but poor cache performance makes it slower than Quick Sort in practice.

Use Cases

Memory-constrained environmentsGuaranteed worst-case performance