Choose the next smallest.
Trace a simple selection invariant and understand why fewer swaps do not mean fast growth.
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.
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]))[1, 2, 3, 4]
03 Under the hood
- 1
The inner loop identifies the minimum in the unsorted suffix. It does not move values until the candidate is chosen.
- 2
The swap extends the sorted prefix by one. Copying the input gives this function a nonmutation contract but adds linear auxiliary storage.
- 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
Verify the algorithm against sorted() for empty input and duplicates.
Reveal one possible solution +
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
What is final after each outer pass?
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 ↗.