Picking the shortest kid each time

Selection Sort

The analogy

Scan the whole line and find the very shortest kid, then bring them to the front. Now scan the rest, find the shortest of those, put them second. You look a lot but you barely move anyone — one swap per round.

Visualizer

Watch it select

step 1 / 54
5
3
8
1
9
2
7
4

8 numbers, out of order. Press play — or step through one comparison at a time.

def selection_sort(a):
    n = len(a)
    for i in range(n - 1):
        lo = i
        for j in range(i + 1, n):
            if a[j] < a[lo]:
                lo = j
        a[i], a[lo] = a[lo], a[i]   # one swap per round
    return a
Check yourself

How many swaps does selection sort make?