TExcelTAD
Home › Data Structures & Algorithms › Selection Sort

Selection Sort

Selection sort builds the sorted array from the front. On each pass it selects the smallest value in the unsorted part and swaps it into the first unsorted position. After pass 1 the smallest value is at index 0, after pass 2 the second smallest is at index 1, and so on.

How it works

  1. Look through a[0..n-1], find the index of the smallest value, and swap it with a[0].
  2. Look through a[1..n-1], find the smallest, and swap it with a[1].
  3. Continue until only one value is left; it must be the largest.

In the animation the purple bar is the smallest value found so far in the current pass and the yellow bar is the value being checked against it.

Implementation

python · try it yourself
def selection_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        min_index = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_index]:
                min_index = j
        if min_index != i:
            arr[i], arr[min_index] = arr[min_index], arr[i]
            print(f"Swap {arr[i]} into position {i}: {arr}")
        else:
            print(f"{arr[i]} is already at position {i}: {arr}")
    return arr

print(selection_sort([29, 10, 14, 37, 13]))
Swap 10 into position 0: [10, 29, 14, 37, 13]
Swap 13 into position 1: [10, 13, 14, 37, 29]
14 is already at position 2: [10, 13, 14, 37, 29]
Swap 29 into position 3: [10, 13, 14, 29, 37]
[10, 13, 14, 29, 37]

Compare the printed lines with the animation: the same four passes, the same swaps (pass 3 needs no swap, because 14 is already the smallest of the remaining values [14, 37, 29]).

Counting the work

Selection sort always scans the whole unsorted part, so the number of comparisons does not depend on the data: (n-1) + (n-2) + … + 1 = n(n-1)/2. The number of swaps, however, is at most n - 1, which is much less than bubble sort's worst case.

python · try it yourself
def selection_sort_count(arr):
    n = len(arr)
    comparisons = swaps = 0
    for i in range(n - 1):
        min_index = i
        for j in range(i + 1, n):
            comparisons += 1
            if arr[j] < arr[min_index]:
                min_index = j
        if min_index != i:
            arr[i], arr[min_index] = arr[min_index], arr[i]
            swaps += 1
    return comparisons, swaps

for data in ([1, 2, 3, 4, 5, 6], [6, 5, 4, 3, 2, 1], [3, 1, 6, 2, 5, 4]):
    comps, swaps = selection_sort_count(list(data))
    print(f"{data}: {comps} comparisons, {swaps} swaps")
[1, 2, 3, 4, 5, 6]: 15 comparisons, 0 swaps
[6, 5, 4, 3, 2, 1]: 15 comparisons, 3 swaps
[3, 1, 6, 2, 5, 4]: 15 comparisons, 4 swaps

All three inputs need 15 comparisons. Few swaps make selection sort attractive when writing is much more expensive than reading (for example on flash memory).

Selection sort is not stable

The long-distance swap can jump a value over an equal one. Here two cards have the value 5; the first-listed one (5♠) ends up after 5♥:

python · try it yourself
def selection_sort_by(items, key):
    n = len(items)
    for i in range(n - 1):
        m = i
        for j in range(i + 1, n):
            if key(items[j]) < key(items[m]):
                m = j
        items[i], items[m] = items[m], items[i]
    return items

cards = [(5, "S"), (3, "D"), (5, "H"), (2, "C")]
print(selection_sort_by(cards, key=lambda c: c[0]))
[(2, 'C'), (3, 'D'), (5, 'H'), (5, 'S')]

On the first pass (2, "C") is swapped with (5, "S"), which sends 5S to the back, behind 5H. Bubble sort and insertion sort never do this.

Properties

Property Selection sort
Time (best, average, worst) O(n²): always n(n-1)/2 comparisons
Swaps at most n - 1
Extra memory O(1), in place
Stable? No (in the usual swap form)
Adaptive? No: sorted input takes as long as random input

Tip: A "find the minimum" helper is the heart of selection sort. If you replace the linear scan with a heap that finds the minimum in O(log n), you get heap sort, an O(n log n) algorithm (see Heaps & Priority Queues).

Test yourself

What does pass i of selection sort do?

  1. Swaps every pair of neighbours that is out of order
  2. Finds the smallest unsorted value and swaps it into position i
  3. Inserts a[i] into the sorted prefix
  4. Splits the array in half

How many comparisons does selection sort make on an already sorted array of 6 values?

  1. 5
  2. 6
  3. 15
  4. 36

What is the maximum number of swaps selection sort performs on n values?

  1. n - 1
  2. n
  3. n(n-1)/2
  4. n²