Developer Toolbox

Insertion sort

Builds a sorted part on the left, one value at a time. Each new value is taken out and moved left until it reaches a smaller value.

  • Ω(n)
  • Θ(n²)
  • O(n²)
  • O(1)
  • yes
  • yes
  • comparing
  • moving
  • in hand
  • sorted part
  • in final place
0 / 372 steps

Pairs out of order: 154 (at the start: 154) out of order put in order

Comparisons Shifts

Press play: the lines show how the cost grows as the sort runs

Press play or step through the algorithm.

Space: play or pause. Left and right arrows: step. Home and End: jump.

Try this: Pick a nearly sorted list. Almost nothing shifts, so it finishes in very few steps.

How it works

The left part is always sorted. Take the next value out, move every bigger value in the sorted part one place to the right, then put the value into the gap. This is how many people sort playing cards in their hand.

When it is a good choice

A good choice for short lists and for lists that are almost sorted, where it is very fast. Real sorting libraries use it for the small pieces of a list inside faster methods.