StringMash.com

Insertion sort visualizer

Watch each item slide left into its place among the ones before it.

22 characters
Updates as you type
The animation is below

Show the steps
  1. Take 11 and insert it into the sorted part on its left.
  2. Take 13 and insert it into the sorted part on its left.
  3. Take 5 and insert it into the sorted part on its left.
  4. Take 6 and insert it into the sorted part on its left.
  5. Take 7 and insert it into the sorted part on its left.
  6. Take 3 and insert it into the sorted part on its left.
  7. Sorted in 19 comparisons and 16 moves.

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 each item as it is taken and inserted.

How insertion sort works

Insertion sort keeps a sorted part at the front of the list. It takes the next item, compares it with its left neighbour, and slides it left past every item bigger than it. When it meets one that isn't bigger, it stops: the item is in place among the sorted ones, and the next item takes its turn.

It's how most people sort a hand of cards: pick up the next card and slide it into the right spot among the ones already held.

Quick on lists that are nearly sorted

On a list in reverse order, insertion sort needs n × (n − 1) ÷ 2 comparisons, 45 for ten items. But on a list that's already sorted, each item is checked once and stays put: nine comparisons for ten items. The closer the list is to sorted, the less work it does.

That's why insertion sort survives inside much faster sorts. Quicksort, introsort and Timsort implementations switch to it for small pieces of the list, where its simplicity beats the overhead of anything cleverer.

Questions

Is insertion sort stable?

Yes. An item only moves past items strictly bigger than it, so equal items keep their order.

Why does it say moves rather than swaps?

Each step slides the item one place left past a bigger one. Counted as moves, the total shows how far items had to travel.

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.