Loading controls...

Heap Sort Settings

Parent nodes are greater than children (creates ascending order)

Loading visualization...
Time: O(n log n)
Space: O(1)

Legend

Comparing
Elements being compared
Swapping
Elements being swapped
Sorted
Elements in final position
Unsorted
Elements not yet processed
How to read the visualization:
  • • Numbers show element values
  • • Bottom labels show array indices
  • • Colors indicate current operation
  • • Height represents value magnitude

Inspector

No active frame to inspect

Reference implementation of Heap Sort. Select a language tab to view and copy the code.

def heap_sort(arr: list[int]) -> None:
    n = len(arr)
    for i in range(n // 2 - 1, -1, -1):
        _heapify(arr, n, i)
    for i in range(n - 1, 0, -1):
        arr[0], arr[i] = arr[i], arr[0]
        _heapify(arr, n, i)

def _heapify(arr: list[int], n: int, i: int) -> None:
    largest = i
    left, right = 2 * i + 1, 2 * i + 2
    if left  < n and arr[left]  > arr[largest]: largest = left
    if right < n and arr[right] > arr[largest]: largest = right
    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i]
        _heapify(arr, n, largest)

Python — Code Walkthrough

  1. Phase 1 — build heap with range step -1

    for i in range(n // 2 - 1, -1, -1): _heapify(arr, n, i)

    range(start, stop, step) with step = -1 counts downward. Starting at n//2 − 1 (last non-leaf) and ending at 0 builds the heap bottom-up. The stop value -1 means we include index 0.

  2. Phase 2 — extract and reduce heap size

    for i in range(n - 1, 0, -1): arr[0], arr[i] = arr[i], arr[0]; _heapify(arr, n, i)

    i decrements from n-1 to 1. Each iteration swaps the max (root) to position i and then heapifies the reduced heap of size i. Note n is i here, shrinking the heap boundary.

  3. Leading underscore convention

    def _heapify(arr, n, i)

    The _ prefix is a Python convention for "internal/private". It signals that _heapify is a helper for heap_sort and is not intended to be part of the public interface.

  4. Child index arithmetic

    left, right = 2 * i + 1, 2 * i + 2

    Same 0-indexed array-based heap formula as all other languages. Multiple assignment sets both child indices in one line.

  5. Tuple swap on mismatch

    arr[i], arr[largest] = arr[largest], arr[i]; _heapify(arr, n, largest)

    Python's simultaneous assignment swaps without a temp variable. The recursive call then sifts the displaced element down to restore the heap property.