lou.tools
EN

Insertion sort

Insertion sort, step by step

Watch it sort any list, step by step, with its pseudocode and its Python.

Updated

Free, in your browser. Your lists never leave it.Privacy

The first value alone is in order.

Comparisons: 0Shifts: 0

What happens next?

The run stops five times and asks what comes next. Answer, and it plays on.

Pseudocode and implementation

Pseudocode

  1. The first value alone is a list in order.
  2. Take each next value, from left to right, and hold it aside: it is the one to insert.
  3. While there is a value on its left and that value is greater than the one held:
  4. move that greater value one place to the right.
  5. Put the held value in the gap that is left.
  6. Return the sorted list.

Python

def insertion_sort(a):    for i in range(1, len(a)):        key = a[i]        j = i - 1        while j >= 0 and a[j] > key:            a[j + 1] = a[j]            j -= 1        a[j + 1] = key    return a

How it works

Insertion sort keeps the left part of the list in order. It starts with the first value alone, then takes the next value, holds it aside, and moves every greater value on its left one place to the right. The held value goes into the gap that is left. It is how many people sort the cards in their hand.

Each shift fixes exactly one pair of values that were out of order, so the number of shifts is the number of such pairs. A sorted list needs no shifts and n − 1 comparisons; a list in reverse order needs about n²/2 of each.

It needs no extra memory, and it never moves a value past an equal one, so it is stable. On short or nearly sorted lists it is one of the fastest sorts, which is why faster sorts often switch to it for small pieces.

Complexity

Best caseO(n)
Average caseO(n²)
Worst caseO(n²)
Extra spaceO(1)
StableYes
In placeYes

n is how many values the list has.

Questions

When is insertion sort a good choice?
For short lists and for lists that are nearly sorted, where it does little more than one comparison per value. For long random lists, merge sort or quicksort are much faster.
How is it different from bubble sort?
Both are O(n²) in the worst case and stable. Insertion sort grows a part in order from the left and slides each new value into it; bubble sort carries the greatest value to the end on each pass. Insertion sort usually makes fewer comparisons.
What is the most common mistake?
Swapping the value step by step instead of holding it aside. Keeping it in key and shifting the greater values writes each of them once, and the held value is written once, in its gap.
How does "What happens next?" work?
It runs insertion sort on a new random list and stops five times to ask what comes next: whether a value moves right, which pair is compared, or how the list looks after a value is inserted. Your answers stay in your browser.

More algorithms