Back

Selection Sort

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 Selection Sort. Select a language tab to view and copy the code.

def selection_sort(arr: list[int]) -> None:
    n = len(arr)
    for i in range(n - 1):
        min_idx = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_idx]:
                min_idx = j
        if min_idx != i:
            arr[i], arr[min_idx] = arr[min_idx], arr[i]

Python — Code Walkthrough

  1. Type hints and in-place return

    arr: list[int]) -> None

    The function modifies the list in place and returns None. Python lists are mutable objects; passing arr gives access to the same underlying list.

  2. Outer range

    for i in range(n - 1)

    Iterates over every position that needs to be filled. range(n − 1) stops one before the last element because the final element is already in place after all preceding passes.

  3. Track minimum with a variable

    min_idx = i

    Stores the index of the smallest element found so far in the unsorted portion. Updated inside the inner loop when a smaller element is encountered.

  4. Inner range starts at i+1

    for j in range(i + 1, n)

    Only scans the unsorted part of the array. range(i + 1, n) generates indices i+1 through n−1, skipping the already-sorted prefix.

  5. Conditional tuple swap

    if min_idx != i: arr[i], arr[min_idx] = arr[min_idx], arr[i]

    Skips the swap if the minimum is already in position. Python's simultaneous assignment makes the swap a one-liner with no temp variable.