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 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 neighbor, 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.
A worked example
Sort 5, 2, 4, 6, 1, 3. 2 moves left past 5. 4 moves left past 5 and stops at 2. 6 is already bigger than 5, so it stays. 1 moves left past all four of 6, 5, 4 and 2. Last, 3 moves past 6, 5 and 4 and stops at 2. That's 12 comparisons and 9 moves.
On the same six numbers already in order, it takes 5 comparisons and no moves. In reverse order, 6, 5, 4, 3, 2, 1, every item moves all the way left: 15 comparisons and 15 moves.
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 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






