/utils

Selection Sort

Repeatedly pick the smallest remaining value and swap it to the front. Always n(n − 1)/2 comparisons, but at most n − 1 swaps.

SolvesSorting

best
O(n^2)
average
O(n^2)
worst
O(n^2)
space
O(1)

Selection sort builds the result from the front. Each round it looks at everything that is still unsorted, finds the smallest value and puts it next in line.

Already sorted: every pass finds its minimum in place, so no value moves. It still makes n(n − 1)/2 comparisons: Θ(n²).

10i21324354657687
1def selection_sort(a):2    n = len(a)3    for i in range(n - 1):4        smallest = i5        # find the smallest value in a[i..n)6        for j in range(i + 1, n):7            if a[j] < a[smallest]:8                smallest = j9        a[i], a[smallest] = a[smallest], a[i]10    return a
1 / 50

a[0..-1] holds the 0 smallest values. Find the next one.

comparisons
0
swaps
0

How it works

The array is split into a sorted prefix a[0..i) and the unsorted rest. The prefix holds the i smallest values in their final places [1].

  1. Assume a[i] is the smallest value of the rest.
  2. Scan a[i+1..n). Whenever a value is smaller, remember its index.
  3. Swap the smallest value with a[i]. The prefix is now one value longer.

After n−1n - 1 rounds the last value is also in place.

Complexity

CaseInputComparisonsSwapsTime
Bestsortedn(n−1)2\frac{n(n-1)}{2}n−1n - 1O(n2)O(n^2)
Averagerandomn(n−1)2\frac{n(n-1)}{2}n−1n - 1O(n2)O(n^2)
Worstsmall value at the endn(n−1)2\frac{n(n-1)}{2}n−1n - 1O(n2)O(n^2)

The scan never stops early, so the comparisons do not depend on the input. Round ii compares n−1−in - 1 - i pairs. The swaps are always n−1n - 1, but on sorted input each one swaps a value with itself.

Implementations

  • Standard: one scan per round, one swap per round.

Pitfalls

  • The sort is not stable. Swapping a[i] with a far-away minimum can jump over an equal value. Sorting [2a, 2b, 1] gives [1, 2b, 2a].
  • Sorted input is not faster. Selection sort cannot see that the rest is already in order.

Related

References

  1. T. H. Cormen et al., Introduction to Algorithms, 3rd ed., MIT Press, 2009.

Further reading

  • D. E. Knuth, The Art of Computer Programming, Volume 3: Sorting and Searching, 2nd ed., Addison-Wesley, 1998.
  • K. Mehlhorn and P. Sanders, Algorithms and Data Structures: The Basic Toolbox, Springer, 2008.

Full bibliography