B2.4.3 · Sorting
Selection sort
Python · step by step
Selection sort
Watch the list change while following the actual Python execution.
Python implementation
1def selection_sort(items):2 for start in range(len(items) - 1):3 smallest = start4 for j in range(start + 1, len(items)):5 if items[j] < items[smallest]:6 smallest = j7 items[start], items[smallest] = items[smallest], items[start]8 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 →