Sub topic 5
Selection Sort: Repeatedly Picking the Minimum
This chapter assumes you can read Python loops and index into lists, that you know Big-O notation, and that you have read the earlier chapters on the cost model (comparisons, swaps, shifts, extra space) and on bubble sort. Selection sort uses the same in-place setting as bubble sort, but it divides the work differently. Bubble sort makes many small local swaps. Selection sort scans for one value and then makes a single swap.
The Working Model
Split the array into two regions:
- A sorted prefix
a[:i]holds theismallest values in their final positions. - An unsorted suffix
a[i:]holds everything else in arbitrary order.
Each pass scans the suffix to find the position of its minimum and then swaps that minimum into a[i]. The prefix grows by one element and the suffix shrinks by one. After n - 1 passes the suffix has one element left. That element must be the largest, so it is already in place.
Bubble sort settles the largest remaining value at the right end of the array by moving it through repeated adjacent swaps. Selection sort settles the smallest remaining value at the left boundary of the suffix with one swap that may jump any distance.
The Implementation
def selection_sort(a):
n = len(a)
for i in range(n - 1):
# a[:i] is sorted and holds the i smallest values.
m = i
for j in range(i + 1, n):
if a[j] < a[m]:
m = j
if m != i:
a[i], a[m] = a[m], a[i]
return a
print(selection_sort([64, 25, 12, 22, 11])) # [11, 12, 22, 25, 64]Some details of this code matter:
mstores an index, not a value. You need the index to perform the swap. If you track only the minimum value, you lose track of where it came from.- The inner loop starts at
i + 1. Positioniis already the current candidate, so comparing it with itself would waste a comparison. - The comparison is strict (
<). When several elements tie for the minimum, the scan keeps the first one it found. This choice does not make the algorithm stable, as a later section explains, but it avoids pointless index updates. - The
m != iguard skips swaps that would exchange an element with itself. The result is still correct without the guard. The guard matters when you count writes.
Tracing by Hand
Trace [64, 25, 12, 22, 11]. In each row, the sorted prefix is to the left of the bar.
| Pass i | Suffix scanned | Comparisons | Min found (index) | Swap | Array after pass | Column |
|---|---|---|---|---|---|---|
| 0 | 64, 25, 12, 22, 11 | 4 | 11 (4) | a[0] and a[4] | 11 \ | 25, 12, 22, 64 |
| 1 | 25, 12, 22, 64 | 3 | 12 (2) | a[1] and a[2] | 11, 12 \ | 25, 22, 64 |
| 2 | 25, 22, 64 | 2 | 22 (3) | a[2] and a[3] | 11, 12, 22 \ | 25, 64 |
| 3 | 25, 64 | 1 | 25 (3) | none | 11, 12, 22, 25 \ | 64 |
The trace uses 10 comparisons and 3 swaps. In pass 0, the value 64 jumped from the front of the array to the back in one swap. Bubble sort cannot do that, because it moves an element at most one position per swap in the direction opposite to its bubbling.
When you trace by hand, write down the candidate index m after each comparison and not just the final result. Most tracing mistakes happen when someone updates m from a value that is not actually smaller than the current candidate.
Counting the Work
Comparisons Do Not Depend on the Input
Pass i compares every element of the suffix after position i against the current candidate. That is n - 1 - i comparisons. Summed over all passes:
(n − 1) + (n − 2) + … + 1 = n(n − 1) / 2
This total is exact for every input. Sorted, reversed, and random arrays of the same length all cost the same number of comparisons. The scan cannot stop early, because no element can be ruled out as the minimum until every element has been seen. Selection sort is therefore non-adaptive: it gets no benefit from input that is already nearly sorted.
Swaps Are Bounded by n − 1
Each pass performs at most one swap, so the total is at most n - 1. With the m != i guard, a sorted array needs zero swaps. The instrumented version below shows how the comparison count stays fixed while the swap count changes with the input:
def selection_sort_counted(a):
n = len(a)
comparisons = swaps = 0
for i in range(n - 1):
m = i
for j in range(i + 1, n):
comparisons += 1
if a[j] < a[m]:
m = j
if m != i:
a[i], a[m] = a[m], a[i]
swaps += 1
return comparisons, swaps
inputs = {
"sorted": [1, 2, 3, 4, 5],
"reversed": [5, 4, 3, 2, 1],
"rotated": [2, 3, 4, 5, 1],
"example": [64, 25, 12, 22, 11],
}
for name, data in inputs.items():
print(name, selection_sort_counted(list(data)))
# sorted (10, 0)
# reversed (10, 2)
# rotated (10, 4)
# example (10, 3)The reversed array needs only 2 swaps, which surprises many people. Swapping 1 into position 0 also moves 5 into position 4, so each swap fixes two elements. The rotated input [2, 3, 4, 5, 1] reaches the maximum of n - 1 = 4 swaps, because each swap fixes only one element and pushes the displaced value one slot further along.
Extra Space
The algorithm needs only the indices i, j, and m, plus one temporary value during a swap. That is O(1) auxiliary space, so selection sort is a true in-place sort.
When Few Writes Matter
Because selection sort performs so few writes, it is a reasonable choice when writing is much more expensive than reading. Some examples:
- Data on flash memory or EEPROM, where every write wears the medium and takes far longer than a read.
- Arrays of large records stored by value, where each swap copies many bytes. Comparing keys is cheap in comparison.
- Situations where each move triggers an external side effect, such as physically rearranging items or sending an update over a network.
When records are large, a common alternative is to sort an array of indices or pointers and leave the records where they are. If you cannot do that and must move the records themselves, selection sort keeps the number of moves low. When writes and reads cost about the same, its fixed n(n − 1)/2 comparisons make it slower in practice than insertion sort on most inputs. A later chapter compares the three sorts side by side.
Common Errors
Swapping Inside the Inner Loop
def broken_selection_sort(a):
n = len(a)
for i in range(n - 1):
for j in range(i + 1, n):
if a[j] < a[i]:
a[i], a[j] = a[j], a[i] # swaps on every improvement
return a
print(broken_selection_sort([64, 25, 12, 22, 11])) # [11, 12, 22, 25, 64]This version still produces sorted output, so tests that only check the result will pass. However, it swaps every time it finds a new candidate minimum, which brings the swap count back to O(n²) and removes the low-write advantage. It also shuffles elements around in the suffix more than necessary. Check swap counts as well as results when you test an implementation that is supposed to be selection sort.
Tracking the Value Instead of the Index
If you write smallest = a[i] and then smallest = a[j], you can no longer perform the swap without a second search. A second search costs extra comparisons, and with duplicate values it can find a different position than the one you meant.
Off-by-One Boundaries
Running the outer loop as range(n) is harmless: the last pass scans an empty range and makes no swap. Starting the inner loop at 0 instead of i + 1 is a real bug, because the scan can then select an element that is already in the sorted prefix and swap it back out.
Stability, in Brief
Selection sort as written above is not stable. The long-distance swap can carry an element past another element with an equal key, which reverses their original order. For example, [(2, 'a'), (2, 'b'), (1, 'c')] sorted by the first field becomes [(1, 'c'), (2, 'b'), (2, 'a')]. The stability chapter walks through this example and explains why the strict < comparison does not prevent it.
Variants Worth Knowing
Selecting the Maximum from the Right
You can scan for the maximum and swap it into the last position of the unsorted region. This is the same algorithm mirrored, with the same counts. It is useful when it fits the surrounding code more naturally, for example when the sorted region needs to grow from the right end.
Double-Ended Selection
Each pass can find both the minimum and the maximum of the unsorted region and place them at the two ends. This halves the number of passes, but a naive scan does two comparisons per element, so the total stays close to n²/2. The variant also has a well-known trap. If the maximum was sitting at the left end, swapping the minimum into that slot moves the maximum to wherever the minimum used to be. You must update the maximum's index before you perform the second swap.
Heapsort Is Selection Sort with a Better Scan
The expensive step in selection sort is the linear scan that finds the minimum (or maximum) of the unsorted region. If you store the unsorted region as a binary heap, finding and removing the extreme value costs O(log n) instead of O(n). That change turns selection sort into heapsort, which runs in O(n log n) and is still in place and unstable. This connection is why selection sort is worth understanding beyond small inputs: its overall structure survives in a production-grade algorithm.
Exercise
Trace selection sort on [3, 1, 2, 3, 0]. For each pass, give the index m chosen and the array after the pass. What are the total comparisons and swaps?
Show answer
Pass 0 scans all five elements and picks m = 4 (value 0). Swapping a[0] and a[4] gives [0, 1, 2, 3, 3]. Pass 1 picks m = 1 (value 1), so no swap. Pass 2 picks m = 2, so no swap. Pass 3 compares a[3] = 3 with a[4] = 3. The comparison is strict, so m stays 3 and there is no swap. The totals are 4 + 3 + 2 + 1 = 10 comparisons and 1 swap.
Exercise
For n = 6, give an input that forces selection sort (with the m != i guard) to make exactly 5 swaps, and an input that makes it do 0 swaps. How many comparisons does each input require?
Show answer
The left rotation [2, 3, 4, 5, 6, 1] forces 5 swaps, because each pass moves the smallest value one step closer to its slot and fixes only one element. The sorted input [1, 2, 3, 4, 5, 6] needs 0 swaps. Both inputs require exactly 6 × 5 / 2 = 15 comparisons, because selection sort's comparison count does not depend on the input.
Exercise
A colleague's "selection sort" passes every correctness test, but on 1,000 random elements it performs about 3,000 swaps instead of at most 999. What is the most likely bug?
Show answer
The swap is inside the inner loop. The code swaps a[i] with a[j] every time it finds a smaller value, instead of recording the index m and swapping once after the scan. The output is still sorted, but each pass can make several swaps, so the low-write property of selection sort is lost.