Selection Sort
Repeatedly select the minimum of the unsorted suffix and swap it into place; exactly n−1 swaps.
You have not marked these as done yet. Read on anyway if they feel familiar; come back to them if something here does not land.
Overview
Selection sort grows a sorted prefix one element at a time: scan the unsorted suffix for its minimum and swap it to the front of the suffix. It always does n(n-1)/2 comparisons regardless of input — it is not adaptive — but at most n - 1 swaps, the fewest writes of any general comparison sort.
It is in-place and, in its usual swap-based form, not stable (swapping the minimum into position can jump an equal element over another). Its niche is when writes are far more expensive than reads, e.g. flash memory with limited write cycles or huge records where moving is costly.
Intuition
A mental model before the formal terms.
Sorting a hand of cards by repeatedly scanning for the smallest card you have not placed yet and moving it to the next slot on the left. You look at every remaining card each time, but you only ever move one card per round.
How it works
- For
i = 0 … n - 2, setminIdx = i. - Scan
j = i + 1 … n - 1; ifa[j] < a[minIdx], setminIdx = j. - Swap
a[i]witha[minIdx]. - After the loop, the whole array is the sorted prefix.
Why it works
Invariant: after iteration i, a[0..i] contains the i + 1 smallest elements in sorted order, and every element of a[i+1..] is ≥ a[i].
The scan finds the true minimum of the suffix, which is exactly the next element in sorted order; placing it at i extends the invariant.
Recognition
How to tell a problem wants this.
- The problem restricts the number of writes/swaps rather than comparisons.
- You need a predictable, data-independent running time (e.g. constant-time side-channel resistance on small arrays).
- Asked to explain why a sort is unstable and how to fix it (shift instead of swap at
O(n²)writes).
Interactive visualization
Play, step, change the input. ← → and space work too.
1for i in 0 .. n-2:2 minIdx = i3 for j in i+1 .. n-1:4 if a[j] < a[minIdx]:5 minIdx = j6 swap(a[i], a[minIdx])Pseudocode
1for i from 0 to n - 2:2 minIdx = i3 for j from i + 1 to n - 1:4 if a[j] < a[minIdx]: minIdx = j5 swap(a[i], a[minIdx])Implementations
1def selection_sort(a: list[int]) -> None:21 · Setup3 n = len(a)42 · Grow the sorted prefix one slot at a time5 for i in range(n - 1):63 · Find the minimum of the unsorted suffix7 min_idx = i8 for j in range(i + 1, n):9 if a[j] < a[min_idx]:10 min_idx = j114 · Swap it into place (at most one write pair per pass)12 if min_idx != i:13 a[i], a[min_idx] = a[min_idx], a[i]range(i + 1, n)scans the unsorted suffix; onn <= 1the outerrange(n - 1)is empty.- Tracking
min_idx(not the value) lets the tuple swap target the slot directly. - One swap per pass — the minimum-writes property.
- No early exit: comparisons are always
n(n-1)/2.
min(range(i, n), key=a.__getitem__) does the scan in C but is still O(n) per pass.
min(range(i, n), key=a.__getitem__)returns the index of the minimum in one expression.- Python
list.sort()is stable; selection sort is not — usesorted(a, key=...)for real work. - The tuple swap is atomic from the reader's point of view; no temp variable needed.
- Using
a.index(min(a[i:]))— the slice copies andindexfinds the first match in the whole list, not the suffix. - Swapping inside the inner loop.
- Assuming stability.
- Swap-based selection sort is unstable in every language; the stable variant (shift instead of swap) costs O(n²) writes and loses the minimal-writes advantage.
- C++
std::min_element/std::iter_swapand Pythonmin(range, key=)express the inner scan with library calls; JS/TS have no index-returning min and need the manual loop. - Library sorts are stable in Python and JS (since ES2019) but
std::sortis not — usestd::stable_sortwhen equal keys must keep order. - Numeric
[10, 2, 5].sort()in JS/TS sorts as strings; C++ and Python compare numbers.
Complexity
Always n(n−1)/2 comparisons; at most n−1 swaps. In-place, not stable, not adaptive.
Compare growth rates in the Complexity Explorer →When to use — and when not to
- Writes are expensive and must be minimized (EEPROM/flash, large records moved by value).
- Very small arrays where simplicity matters and input order is arbitrary.
- When a data-independent number of comparisons is desired.
- Nearly sorted input — selection sort does not benefit; Insertion Sort runs in
O(n). - Stability is required (use insertion sort or Merge Sort).
- Anything beyond a few hundred elements.
Alternatives
Common mistakes
- Believing it is stable;
[2a, 2b, 1]becomes[1, 2b, 2a]. - Swapping inside the inner loop whenever a smaller element is seen — that is a different, slower algorithm with
O(n²)swaps. - Running the outer loop to
n - 1inclusive (harmless but wasteful).
Interview patterns
- Contrast with Heap Sort: heap sort is selection sort with an
O(log n)"find minimum" instead ofO(n). - Make it stable by inserting the minimum via shifting rather than swapping.
- Bidirectional (double-ended) selection sort picks min and max each pass.
- Recognizing the approach from an array and a targetIntermediate
- When space complexity mattersIntermediate
- Two pointers or hash map?Intermediate
- Convincing me your algorithm is correctExpert
- Two SumBeginner
Example problems
Check yourself
Answer out loud or on paper first, then compare. These come from the interview questions linked to this lesson.
Given an array and a target, how would you determine which algorithmic approach to use?
Show a strong answerHide the answer
A strong candidate does not answer with an algorithm. They answer with questions, and each question maps to a technique. Is the array sorted? Sorted plus a target means Binary Search for one element (
O(log n)) or Two Pointers (Opposite Ends) for a pair (O(n)). Do I need a pair, a subarray, or a subsequence? A pair with arbitrary order is a Hash Map problem (O(n)time,O(n)space). A contiguous subarray with a sum target is Prefix Sum plus a hash map of seen prefixes. A subsequence usually means Dynamic Programming or backtracking.Are the values constrained? All positive means a sliding window can grow and shrink monotonically (Sliding Window (Variable Size)); negatives break that monotonicity and force prefix sums. Small integer ranges (say
0..10^5) allow counting arrays instead of hash maps. What size is `n`?n ≤ 20invites2^nenumeration;n ≤ 5000toleratesO(n^2);n ≤ 10^5demandsO(n log n)or better.They then say the brute force out loud — usually
Full interview question, with follow-ups and red flags →O(n^2)over pairs orO(n^2)over subarrays — and identify what the inner loop is *looking for*. That inner lookup is the thing a hash map, a sorted order, or a running window replaces. This is the general engine: name the repeated question the brute force asks, then pick the structure that answers it inO(1)orO(log n).Interviewers ask about space complexity. When does it actually matter, and how do you reason about it?
Show a strong answerHide the answer
Space complexity counts auxiliary memory beyond the input: explicit structures (hash maps, DP tables), the recursion stack, and sometimes the output itself if it is large. A strong candidate lists all three; the recursion stack is the one people forget — recursive DFS on a tree is
O(h), and on a degenerate treeh = n.It matters in three situations. Memory limits: a
10^5 × 10^5DP table is10^{10}cells — impossible — so you need a 1D rolling array or a different state. Streams: if data is unbounded you must keepO(k)orO(1)state (top-kwith a heap, reservoir sampling). Explicit requirements: "in place" or "O(1)extra space" forces two pointers, index marking, or bit tricks instead of a hash set.The standard reductions: a 2D DP that only reads the previous row becomes two rows (Grid DP, Longest Common Subsequence); a hash set used for "seen" can become a sort plus adjacent comparison when reordering is allowed; recursion becomes an explicit loop; and a full array of prefix sums becomes a running sum when only the current prefix is needed. They also weigh the tradeoff honestly: an
Full interview question, with follow-ups and red flags →O(n)hash map that turnsO(n^2)intoO(n)is almost always worth it.The array is sorted and I need two elements summing to the target. Hash map or two pointers?
Show a strong answerHide the answer
Two pointers: same
Full interview question, with follow-ups and red flags →O(n)time butO(1)space and no hashing overhead. A hash map only wins if the array is unsorted and sorting is not allowed or indices must be preserved.