StringMash.com

Selection sort visualizer

Watch it find the smallest item left and move it to the front.

25 characters
Updates as you type
The animation is below

Show the steps
  1. 5 is the smallest left, so it swaps with 29 into position 1.
  2. 10 is already the smallest left, so it stays in position 2.
  3. 13 is the smallest left, so it swaps with 14 into position 3.
  4. 14 is the smallest left, so it swaps with 37 into position 4.
  5. 21 is the smallest left, so it swaps with 37 into position 5.
  6. 29 is already the smallest left, so it stays in position 6.
  7. Sorted in 21 comparisons and 4 swaps.

Watch it sort

  • Being compared
  • Just moved
  • In its final place
  • Not being worked on

Type a list above to see it sorted step by step.

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.