Using the visualizer
Type a list in the box, separated by commas, spaces or new lines. Numbers are sorted by value and words alphabetically, ignoring capitals. The sorted list appears straight away, and the animation below plays the sort one step at a time, up to 24 items.
Play, Step forward, Step back and Speed control the animation, and the key under the bars says what each colour means. Show the steps lists every swap in order.
How selection sort works
Selection sort scans the whole list for the smallest item and swaps it into the first place. Then it scans what's left for the next smallest and swaps that into the second place, and so on. The sorted part grows from the front, one item per round, and nothing in it ever moves again.
In the animation, the faded bars are already sorted, yellow shows the smallest found so far being compared with the next candidate, and orange shows the swap at the end of each round.
Few swaps, many comparisons
Selection sort always makes n × (n − 1) ÷ 2 comparisons, however the list starts: 45 for ten items, even if they're already in order. But it makes at most n − 1 swaps, one per round.
That trade matters when writing is costly. On EEPROM or flash memory, where every write wears the memory out a little, a sort that writes rarely can be worth its extra comparisons.
Questions
Is selection sort stable?
Not as it's usually written. The long-distance swap can jump an item past another one equal to it. The comparison table on the sorting algorithms page shows this for each sort here.
Selection sort or insertion sort?
Insertion sort is usually faster, because it stops early on lists that are nearly in order. Selection sort does the same amount of comparing whatever the input, but swaps far less.
Why does the animation only go up to 3 steps a second?
Each step recolours a bar or two, and three changes a second is the limit the web's accessibility guidelines set for anything that flashes. Step forward goes as fast as you can click.






