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. In a list with both, the numbers come first. 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 color 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 green bars are already in their final place, 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.
A worked example
Sort 5, 2, 4, 6, 1, 3. The first round compares across all six and finds 1, which swaps with 5. The second round finds that 2 is already the smallest left, so nothing moves. The third finds 3 and swaps it with 4, the fourth finds 4 and swaps it with 6, and the fifth finds 5 already in place. That's 15 comparisons and 3 swaps.
The same six numbers in order still take 15 comparisons, but no swaps. In reverse order, it's 15 comparisons and only 3 swaps: 6 trades places with 1, 5 with 2, and 4 with 3, and the list is sorted.
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 recolors a bar or two. The web's accessibility guidelines allow anything that flashes three flashes a second at most, and capping the animation at three steps a second keeps it well inside that. Step forward goes as fast as you can click.
Sources
Added . Last updated and reviewed . What's new






