Visualizer CodeViz · Algorithms, visualized

Part I · Elementary sorts · week 2

Selection sort

Find the smallest remaining key and swap it into place. Insensitive to input: sorted or shuffled, it does exactly the same work.

Run the animation, step by step → generated live from any input you type — nothing is pre-recorded

Cost and properties

compares~n²/2, always
exchangesn
in placeyes
stableno

Reference: Sedgewick & Wayne, §2.1.

Selection sort in Python

Runnable as-is, and written for reading. Watch the highlighted line move through it in the animation, or send it straight to the visualizer — it arrives with a test case ready to run, yours to edit.

Open in Visualizer

def selection_sort(a):
    # INVARIANT: a[0..i-1] is sorted AND every key there is <= every key right of i.
    n = len(a)
    for i in range(n):
        smallest = i                      # index of the smallest key in a[i..n-1]
        for j in range(i + 1, n):
            if a[j] < a[smallest]:
                smallest = j
        a[i], a[smallest] = a[smallest], a[i]
    return a

Why it works

The invariant

Two claims hold at the top of every iteration: a[0..i-1] is in its final sorted order, and nothing to the right of i is smaller than anything to its left. The second half is what makes the left part final rather than merely sorted — selection sort never revisits a placed key.

The cost, and why input does not matter

The inner loop always scans the whole remaining array: (n−1) + (n−2) + … + 1 = ~n2/2 compares, on every input. Only n exchanges though — the fewest of any elementary sort, which is its one real advantage: use it when moving data is far more expensive than comparing it.

Not stable

The long-range swap can jump one equal key past another. With keys B₁ B₂ A, the first pass swaps A with B₁ and the two Bs come out in the wrong relative order. If you need stability, use insertion sort or mergesort.

Watch for

  • smallest updates only on a strictly smaller key, so the earliest of several equal minima wins.
  • The final exchange happens even when smallest == i — a wasted write the textbook version keeps for simplicity.

What to try in the animation

Try already sorted and reverse sorted: the compare count does not move. That is the defining weakness.

The animation is generated from the input box, in your browser — press Animate after editing it. To execute the Python itself, use Open in Visualizer above.

Open Selection sort in the player →

The rest of Elementary sorts