Choose the next smallest.
Trace a simple selection invariant and understand why fewer swaps do not mean fast growth.
01 Model 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.
The prefix contains the smallest values in their final positions.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
FOR each output position
find the minimum in the remaining suffix
swap it into that positionStart with the original values. Predict the next comparison.
Change the experiment +
03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
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]
- 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 Count the cost
O(n²) comparisons in best and worst cases
O(n) for the copied result
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
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")06 Check your reasoning
What is final after each outer pass?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.