Selection sort splits the array into a sorted prefix and an unsorted suffix. Each pass selects the minimum of the unsorted part and swaps it to the end of the prefix, where it never moves again. It always performs about n²/2 comparisons, even on sorted input, but at most n − 1 swaps: the fewest of any simple sort, which matters when writing data is far more expensive than reading it.
Think of it like
Picking players for a lineup
A coach lines players up by height. She scans everyone still on the bench, calls the shortest one forward to the next spot in the line, and repeats. Each player walks to the line exactly once and never moves again, but finding the shortest still means looking at the whole bench every time, no matter how well-ordered the bench already was.
How it works
For each position i from left to right, scan a[i..n-1] to find the index min of the smallest value, then swap a[i] with a[min]. After the swap, a[0..i] holds the i + 1 smallest values in sorted order.
- 1
Assume the first is smallest
Set
min = i, the first index of the unsorted part. - 2
Scan the rest
For each
jfromi + 1ton - 1, ifa[j] < a[min], updatemin = j. - 3
Swap once
Swap
a[i]witha[min](skip it ifmin == i). The minimum is now at its final position. - 4
Grow the sorted prefix
Move to
i + 1. Aftern - 1passes the last element is automatically the largest.
Worked example
Sorting [29, 10, 14, 37, 13]. Each row shows which minimum was selected and where it was swapped.
| Pass | Unsorted part | Minimum | Array after pass | Comparisons |
|---|---|---|---|---|
| 1 | [29, 10, 14, 37, 13] | 10 (index 1) | [10, 29, 14, 37, 13] | 4 |
| 2 | [29, 14, 37, 13] | 13 (index 4) | [10, 13, 14, 37, 29] | 3 |
| 3 | [14, 37, 29] | 14 (already in place) | [10, 13, 14, 37, 29] | 2 |
| 4 | [37, 29] | 29 (index 4) | [10, 13, 14, 29, 37] | 1 |
Complexity analysis
Pass i scans n − 1 − i elements no matter what they contain, because you cannot know an element is the minimum without comparing it with every other candidate. The total is the same arithmetic series in the best, average and worst case.
Comparisons: always Θ(n²)
- n(n − 1)/2 in every case
- Sorted input gives no early exit
- 45 comparisons for 10 elements, about 500,000 for 1,000
Swaps: at most n − 1
- One swap per pass, so O(n) writes in total
- Zero swaps on already-sorted input
- Every element moves directly to its final position
When writes are expensive
Counting comparisons hides an important cost model. Some storage wears out with writes (flash memory and EEPROM cells survive a limited number of erase cycles), and some records are large enough that moving them dominates comparing their keys. In those settings selection sort's O(n) writes can beat algorithms that are faster on paper.
| Algorithm | Comparisons (worst) | Element moves (worst) |
|---|---|---|
| Bubble Sort | n(n − 1)/2 | n(n − 1)/2 swaps |
| Insertion Sort | n(n − 1)/2 | about n²/2 shifts |
| Selection sort | n(n − 1)/2 | n − 1 swaps |
| Cycle sort | Θ(n²) | at most n writes (optimal) |
Why it is unstable
A sort is stable if equal elements keep their original relative order. Selection sort's long-distance swap can carry an element over an equal one. Label two equal keys 5a and 5b and sort [5a, 5b, 3]:
- 1
Pass 1 selects 3
The minimum 3 is at index 2, so it swaps with
a[0] = 5a. The array becomes[3, 5b, 5a]:5ajust jumped over5b. - 2
Pass 2 keeps them
The minimum of
[5b, 5a]is5b(the first one found, since the comparison is strict), which is already in place. - 3
Result
[3, 5b, 5a]. The two 5s are reversed relative to the input, so the sort is not stable.
A stable variant
Instead of swapping, remove the minimum and shift the elements a[i..min-1] one place right, then drop the minimum into a[i]. Nothing ever jumps over an equal element, so the sort becomes stable. The price is that writes climb back to Θ(n²), which removes selection sort's main advantage. On a linked list the same idea is cheap: unlink the minimum node and append it to the output list in O(1).
Variations and relatives
- Double selection sort: find both the minimum and the maximum in each pass and place them at both ends. It halves the number of passes, but the comparison count stays about n²/2 (it drops to roughly 3n²/8 with the pairwise min/max trick).
- Partial selection: stopping after
kpasses yields theksmallest elements in sorted order in O(nk) time, which is fine for very smallk. - Cycle sort: follows each permutation cycle to write every element straight to its final position; useful when writes are extremely costly.
- Heap sort: the same select-the-extreme idea, but with a heap that finds each maximum in O(log n) instead of O(n).
Complexity
| Case | Time | Space | Notes |
|---|---|---|---|
| Best | O(n²) | O(1) | Already sorted: still n(n − 1)/2 comparisons, 0 swaps |
| Average | O(n²) | O(1) | n(n − 1)/2 comparisons, at most n − 1 swaps |
| Worst | O(n²) | O(1) | n(n − 1)/2 comparisons, n − 1 swaps |
| Stable variant | O(n²) | O(1) | Shifting instead of swapping: Θ(n²) writes |
In-place and not adaptive. The swapping version is not stable.
Implementation
Finds the minimum of the unsorted suffix and swaps it into place. At most n − 1 swaps.
def selection_sort(a: list[int]) -> list[int]:
n = len(a)
for i in range(n - 1):
m = i # index of the smallest value seen so far
for j in range(i + 1, n):
if a[j] < a[m]:
m = j
if m != i: # one swap per pass at most
a[i], a[m] = a[m], a[i]
return aKey takeaways
- Each pass selects the minimum of the unsorted suffix and swaps it into its final position.
- Comparisons are always n(n − 1)/2: selection sort is Θ(n²) even on sorted input (not adaptive).
- It makes at most n − 1 swaps, the fewest of the simple sorts, which helps when writes are expensive.
- The long-distance swap makes it unstable; shifting instead of swapping restores stability at the cost of Θ(n²) writes.
- Heap sort is selection sort with a heap: the same idea, with O(log n) selection.
Common pitfalls
- Claiming an O(n) best case: there is no early exit, because finding a minimum always requires a full scan.
- Assuming that a strict
<comparison makes it stable; the swap itself breaks stability. - Swapping inside the inner loop every time a smaller element is found, which turns it into a slower, write-heavy algorithm.
- Choosing it for performance on large inputs: Θ(n²) comparisons make it impractical beyond a few thousand elements.
Interview tips
- Lead with the trade-off: Θ(n²) comparisons in every case, but only O(n) swaps.
- Have a three-element counterexample ready to show why it is unstable, such as
[5a, 5b, 3]. - Connect it to heap sort and to top-k selection; interviewers like hearing how a better data structure fixes a slow algorithm.
Real-world applications
- Sorting on write-limited media such as flash memory or EEPROM, where swaps are costly.
- Tiny arrays in memory-constrained embedded code, where its simplicity and O(1) space matter.
- Finding the k smallest items for very small k without extra memory.
- Teaching loop invariants and the difference between comparisons and writes as cost measures.
Practice problems
Test yourself
How many comparisons does selection sort make on an already-sorted array of 10 elements?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.