Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ The sorting workshop
EXPERIMENT 20 / 66

Choose the next smallest.

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

BY NAVAN SAMI◷ 8 MIN READCOREALGORITHM

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 THING THAT MUST STAY TRUE

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.

the_strategy.txt
FOR each output position
  find the minimum in the remaining suffix
  swap it into that position
ALGORITHM STUDIOLIVE IN YOUR BROWSER
38
0
12
1
57
2
24
3
8
4
46
5
31
6
COMPARISONS 0ARRAY WRITES 0STEP 1/32

Start with the original values. Predict the next comparison.

Change the experiment +
Current operation Ordered / visitedPredict. Step. Explain.

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

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]
  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 Count the cost

TIME

O(n²) comparisons in best and worst cases

SPACE

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

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")

06 Check your reasoning

QUICK SIGNAL CHECK

What is final after each outer pass?

ANOTHER PATTERN IN YOUR TOOLKIT.

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.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.