Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Think in algorithms
EXPERIMENT 70 / 101

Choose the next smallest.

Trace a simple selection invariant and understand why fewer swaps do not mean fast growth.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

Selection sort repeatedly finds the smallest remaining item and places it at the next output position. After each outer iteration, the prefix is in its final sorted position. A basic implementation still examines a quadratic number of candidates, even when the input is already ordered. It can make relatively few swaps, but its comparison growth is the important scalability limitation.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

selection_sort.py
def selection_sort(values):
    result = list(values)
    for start in range(len(result)):
        smallest = start
        for index in range(start + 1, len(result)):
            if result[index] < result[smallest]: smallest = index
        result[start], result[smallest] = result[smallest], result[start]
    return result
print(selection_sort([4, 2, 3, 1]))
↳ EXPECTED OUTPUT
[1, 2, 3, 4]

03 Under the hood

  1. 1

    The inner loop identifies the minimum in the unsorted suffix. It does not move values until the candidate is chosen.

  2. 2

    The swap extends the sorted prefix by one. Copying the input gives this function a nonmutation contract but adds linear auxiliary storage.

  3. 3

    This swap-based form is not stable: moving a distant minimum can reorder equal-key elements. Use built-in sorting for ordinary production work rather than selecting an algorithm only because it is easy to trace.

04 Your turn, builder

A SMALL MISSION

Verify the algorithm against sorted() for empty input and duplicates.

Reveal one possible solution +
one_possible_solution.py
def selection_sort(values):
    result = list(values)
    for start in range(len(result)):
        smallest = min(range(start, len(result)), key=result.__getitem__)
        result[start], result[smallest] = result[smallest], result[start]
    return result
for values in [[], [2, 1, 2], [1, 2, 3]]:
    assert selection_sort(values) == sorted(values)
print("Selection checks passed")

05 Check your signal

QUICK SIGNAL CHECK

What is final after each outer pass?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.