Sub topic 5
Selection Sort: Repeatedly Picking the Minimum
This chapter assumes you can write loops over list indices in Python and read Big-O notation. It also uses the comparison and swap counts introduced in the cost-model chapter.
Selection sort splits the array into two parts. The left part is sorted and final. The right part is unsorted. On each pass, the algorithm scans the unsorted part for its smallest value and swaps that value to the front of the unsorted part. The sorted part then grows by one element.
The working model
At the start of pass i, a[:i] holds the i smallest values in sorted order. Every element in a[i:] is greater than or equal to every element in a[:i]. The pass finds the index m of the minimum in a[i:] and swaps a[i] with a[m]. After n - 1 passes, only one element remains in the unsorted part, and it must be the largest, so the array is sorted.
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]The inner loop only reads from the array. All writes happen in the single swap at the end of each pass.
Tracing by hand
Here is the trace for [64, 25, 12, 22, 11]:
| Pass i | Unsorted part | Minimum (index) | Comparisons | Swap? | Array after pass |
|---|---|---|---|---|---|
| 0 | 64, 25, 12, 22, 11 | 11 (4) | 4 | yes | 11, 25, 12, 22, 64 |
| 1 | 25, 12, 22, 64 | 12 (2) | 3 | yes | 11, 12, 25, 22, 64 |
| 2 | 25, 22, 64 | 22 (3) | 2 | yes | 11, 12, 22, 25, 64 |
| 3 | 25, 64 | 25 (3) | 1 | no | 11, 12, 22, 25, 64 |
Pass 0 also moved 64 from the front to the back. That kind of long-distance move matters for stability, which a later chapter covers.
What it costs
The number of comparisons does not depend on the input. Pass i makes n - 1 - i comparisons, so the total is (n−1) + (n−2) + … + 1 = n(n−1)/2. For five elements that is 10, as the table shows. This holds for sorted, reversed, and random input, so selection sort is Θ(n²) in comparisons in every case.
Swaps are a different matter. Each pass makes at most one swap, so the algorithm makes at most n − 1 swaps in total. It uses O(1) extra space. Few writes is the main strength of selection sort. It is a good fit when moving or writing an element costs much more than comparing two elements, for example with large records or flash memory that wears out with writes.
Common errors
- Comparing against
a[i]instead ofa[m]. If you writeif a[j] < a[i]: m = j,mends up as the last element smaller thana[i], which is not always the minimum. The result is wrong output. - Swapping inside the inner loop. If you swap every time you find a smaller value, the output is still sorted, but the swap count rises to O(n²). That throws away the property that makes selection sort worth using.
- Starting the inner loop at
i. This is still correct, but it wastes one comparison per pass because it comparesa[i]with itself. - Outer loop off by one.
range(n)is harmless because the last pass scans nothing. Stopping atrange(n - 2)leaves the final two elements unsorted.
Exercise
Trace selection_sort on [2, 3, 1]. How many comparisons and how many swaps does it make, and what is the array after each pass?
Show answer
Pass 0 compares 3 with 2, then 1 with 2. That is 2 comparisons, giving minimum 1 at index 2. It swaps to get [1, 3, 2]. Pass 1 compares 2 with 3. That is 1 comparison, giving minimum 2 at index 2. It swaps to get [1, 2, 3]. The totals are 3 comparisons, which equals 3·2/2, and 2 swaps.
Exercise
For an array of 6 elements, how many comparisons does selection sort make if the array is already sorted, and what is the largest number of swaps it can make on any 6-element input?
Show answer
It makes 15 comparisons (6·5/2) whatever the input order. It makes at most 5 swaps (n − 1). A sorted input makes 0 swaps because m always equals i.