programmingconcepts

§ 3.6 · Algorithms

Selection sort

Find the smallest remaining value and swap it to the front of the unsorted part, one pass at a time.

Selection sort splits the list into a sorted front and an unsorted rest. Each pass scans the unsorted part for its smallest value and swaps it to the front, growing the sorted part by one. It always makes about n²/2 comparisons, whatever the input, but never more than n − 1 swaps, which helps when writes are expensive.

Every case
O(n²) comparisons
Swaps
At most n − 1
Extra space
O(1)
Stable
No
Requires
ArraysBig O
def selection_sort(a):
    n = len(a)
    for i in range(n - 1):
        smallest = i
        for j in range(i + 1, n):
            if a[j] < a[smallest]:
                smallest = j
        if smallest != i:
            a[i], a[smallest] = a[smallest], a[i]

Press Play or Step to start.

0 comparisons0 swapsstep 0 / 00 / 12 in placecomparingmovingsmallest so far

Fig. 3.6. Grey marks the smallest value found so far in this pass, blue bars are being compared, and orange bars swap when the pass ends.

Intuition

Picture lining up a class by height. You scan the whole group for the shortest person and send them to the front. Then you scan everyone who’s left for the next shortest, and so on. Each scan finishes one spot for good, and you never revisit it.

How it works

  1. Start at index 0. Assume the value there is the smallest.
  2. Compare it with every value to its right. Whenever one is smaller, remember that one instead.
  3. At the end of the pass, swap the smallest value into index 0. That position is now final.
  4. Move to index 1 and repeat. Stop when one value is left; it is already in place.

The grey bar in the figure is the “smallest so far”. Watch it jump each time a comparison finds something smaller.

Complexity

Case Comparisons Swaps
Best (sorted) n(n − 1)/2 0
Average n(n − 1)/2 about n − 1
Worst n(n − 1)/2 n − 1

The comparison count is fixed: the first pass checks n − 1 values, the next n − 2, and so on down to 1. Unlike insertion sort and bubble sort, it gets no faster on sorted or nearly sorted input. What it saves is swaps: one per pass at most, against up to n²/2 for the other two.

Why it isn’t stable

The long-distance swap can jump a value over an equal one. Sort [4a, 4b, 1]: the first pass swaps 1 with 4a, giving [1, 4b, 4a]. The two 4s have changed order. If you sort records by one field after another, that matters; use a stable sort like merge sort instead.

Common mistakes

  1. Swapping inside the inner loop. Swapping every time a smaller value turns up still sorts, but turns the few swaps into many. Remember the index and swap once at the end of the pass.
  2. Comparing with the wrong value. Compare each value with the smallest found so far, a[smallest], not with a[i].
  3. An extra pass. The outer loop can stop at n − 2; the last value has nowhere else to go.

When to use it

Almost never in production: use the built-in sort. Selection sort is worth knowing because it’s the simplest sort to reason about, it does the fewest writes, and its “pick the smallest, then repeat” idea is exactly what heap sort speeds up with a heap.

Check yourself

Check yourself

How many swaps does selection sort make on [1, 2, 3, 4, 5]?

Check yourself

After two passes over [5, 3, 8, 1, 4], what does the list look like?

Sources

  • Donald Knuth, The Art of Computer Programming, Vol. 3, section 5.2.3, “Sorting by selection.”
  • Robert Sedgewick and Kevin Wayne, Algorithms, 4th edition, section 2.1, “Elementary sorts.”

Newsletter

One new concept each week, by email.

Signup opens soon.