Loading controls...
Loading visualization...
Time: O(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 Insertion Sort. Select a language tab to view and copy the code.

def insertion_sort(arr: list[int]) -> None:
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key

Python — Code Walkthrough

  1. range starts at 1

    for i in range(1, len(arr))

    A one-element prefix [arr[0]] is trivially sorted. range(1, len(arr)) iterates i = 1, 2, … n−1, extending the sorted prefix by one element each pass.

  2. key saves the value

    key = arr[i]

    Python integers are immutable values; assigning key = arr[i] creates an independent copy. This is important because arr[i] will be overwritten in the shifting loop.

  3. j walks left

    j = i - 1

    j starts just left of the current element and decrements while the while condition is true.

  4. Shift and decrement

    while j >= 0 and arr[j] > key: arr[j + 1] = arr[j]; j -= 1

    Python's and short-circuits: j >= 0 is evaluated first, so arr[j] is never read at a negative index. Each iteration copies arr[j] one slot to the right.

  5. Insert after the loop

    arr[j + 1] = key

    When the loop exits, j+1 is the correct insertion point. Python does not need a temp variable here — key was saved upfront.