lou.tools
EN

Selection sort

Selection sort, step by step

Watch it sort any list, step by step, with its pseudocode and its Python.

Updated

Free, in your browser. Your lists never leave it.Privacy

8 values to sort.

Comparisons: 0Swaps: 0

What happens next?

The run stops five times and asks what comes next. Answer, and it plays on.

Pseudocode and implementation

Pseudocode

  1. Take the list; n is how many values it has.
  2. For each position i, from the first to the one before last, take the value at i as the smallest so far:
  3. Walk the values after it, one at a time:
  4. If this value is smaller than the smallest so far,
  5. it becomes the smallest so far.
  6. If the smallest is not already at i, swap it with the value at i.
  7. Return the sorted list.

Python

def selection_sort(a):    n = len(a)    for i in range(n - 1):        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

How it works

Selection sort splits the list into a sorted part on the left, empty at first, and an unsorted part on the right. Each pass walks the whole unsorted part looking for its smallest value, then swaps it into the first unsorted position. The sorted part grows by one value per pass.

It makes the same comparisons whatever the list: n − 1 in the first pass, n − 2 in the second, and so on, about n²/2 in total, even on a list already sorted. What it saves is swaps: at most one per pass, n − 1 in all, which matters when writing a value is expensive.

It needs no extra memory, but it is not stable: the long swap can carry a value past another equal one. Sort 3, 3, 1 and the first 3 ends up after the second.

Complexity

Best caseO(n²)
Average caseO(n²)
Worst caseO(n²)
Extra spaceO(1)
StableNo
In placeYes

n is how many values the list has.

Questions

When is selection sort a good choice?
When a swap costs much more than a comparison, since it makes at most n − 1 swaps, and to learn how sorting works. For real lists of any size, merge sort, quicksort or your language’s own sort are much faster.
How is it different from insertion sort?
Both grow a sorted part from the left. Selection sort looks through every unsorted value to pick the next one, so it always makes about n²/2 comparisons; insertion sort takes the next value as it comes and slides it into place, so a nearly sorted list costs it almost nothing. Insertion sort is stable; selection sort is not.
What is the most common mistake?
Swapping every time a smaller value turns up, instead of only remembering where it is. Keep the position of the smallest so far in m and swap once, at the end of the pass.
How does "What happens next?" work?
It runs selection sort on a new random list and stops five times to ask what comes next: whether a value is the new smallest, which pair is compared, or how the list looks after a pass. Your answers stay in your browser.

More algorithms