Foundation · Module 4 · Lesson 2
Selection Sort
Select the next minimum and grow a sorted prefix.
15–25 min readLesson 20 of 123 Interactive Lab
Lesson 20 of 123
1d streakInteractive Visualization
Trace the algorithm state by state
Change the inputs, run an operation, and connect each visible state change to the explanation below.
Step-through visualizer
Selection Sort
Follow the state transition, then use the controls to test your prediction.
Purple: Current Minimum candidateOrange: Under comparisonGreen: Locked in Sorted Prefix
25
012
138
27
319
42
5startBegin with the entire array as the unsorted partition.
Theory lesson · Step-by-step
Understand Selection Sort
Select the next minimum and grow a sorted prefix.
Worked approach
Trace the reasoning step by step
- 1For each position i, scan the unsorted suffix.
- 2Find its minimum index.
- 3Swap that minimum into position i.
Concrete example
Sort [3, 1, 2] by selecting minima.
- 1Minimum of all values is 1; swap with index 0.
- 2Minimum of [3,2] is 2; swap.
The sorted result is [1, 2, 3].
What must remain true (Loop Invariant)
The prefix before i is sorted and contains the i smallest values.
Reference pseudocode
1for i = 0 to n-2:
2 min = i
3 for j = i+1 to n-1:
4 if a[j] < a[min]: min = j
5 swap(a[i], a[min])
Verify your trace
- • Write the state after every step.
- • Confirm the invariant still holds.
- • Count visited states to derive complexity.
- • Repeat with an edge-case input.
Cost Model
Complexity & Trade-offs
OperationTimeSpaceWhy
Sort
O(n²)
O(1)
Include stability and input shape when comparing sorts.When to use it
- Creating order before searching, grouping, deduplicating, or scanning.
- Selecting records using stability, memory, and input-shape constraints.
- Turning pairwise decisions into monotonic scans.
Common mistakes
- Comparing time alone while ignoring stability and auxiliary memory.
- Breaking duplicate order when stability is required.
- Quoting average performance without worst-case behavior.
Practice prompts
- Reproduce the worked Selection Sort example without looking at the trace.
- Change one input condition and explain whether the Selection Sort invariant still holds.
- Implement the approach, derive its cost, and compare it with a straightforward baseline.
Mastery check
Can you derive it instead of memorizing it?
State the invariant before looking at code.
Explain why every transition is safe.
Construct a worst-case input.
Name one alternative and its trade-off.