B2.4.3 · Sorting

Selection sort

Python · step by step

Selection sort

Watch the list change while following the actual Python execution.

Select Play or Next line to follow Python execution.

Python implementation

The highlight marks the next line to execute. Values show the state before that line.

def selection_sort(items):    for start in range(len(items) - 1):        smallest = start        for j in range(start + 1, len(items)):            if items[j] < items[smallest]:                smallest = j        items[start], items[smallest] = items[smallest], items[start]    return items

Find the smallest remaining item, then swap it into place. The prefix before start is sorted. Comparisons take O(n²) even for sorted input. Auxiliary space is O(1).

Keep exploring

Return to the sorting lesson →

All B2.4 animations →

All practice & resources →