Insertion sort

Like arranging the cards in your hand · Part of Search and sort

Key idea

Practice

6 questions · about 3 min

Explained step by step

Insertion sort

Insertion sort works like sorting the cards in your hand. The first element already counts as sorted. Then the 2nd, called the base, is taken, compared with those to its left, and the larger ones are shifted 1 spot right; the base is written into the gap left. Now the first 2 are sorted. Repeat with the 3rd, the 4th, up to the last.

To trace insertion sort by hand, you mark the sorted part and insert each base. With [4, 1, 3, 2]: base 1 is smaller than 4, 4 shifts: [1, 4, 3, 2]. Base 3 is smaller than 4, 4 shifts: [1, 3, 4, 2]. Base 2 is smaller than 4 and 3, both shift: [1, 2, 3, 4].

In the worst case, with the array reversed, each base shifts all the previous ones: 1 + 2 + ... + (n − 1), about n² / 2. O(n²). But it's adaptive: if the array is already sorted, each base is compared with just 1 neighbor and shifts nothing, so it costs O(n). With almost sorted data, it gets close to that best case. It uses O(1) memory.

Even though it's O(n²), insertion sort is very fast with little data: each step is very simple, a comparison and an assignment. O(n log n) algorithms, like quick sort, do more work per step. That's why many languages, like Java, sort large arrays with quick sort or merge sort, and when the pieces get small, about 16 elements, finish them with insertion sort.

Selection, bubble and insertion sort are all O(n²), but insertion sort is the one used in practice. It beats bubble sort because it shifts instead of swapping: 1 operation per spot against 3. It beats selection sort because it's adaptive, so it works much less with almost sorted data, and because it's stable, so it works for sorting by several criteria.

Stable sort

Insertion sort is stable: when it inserts the base, it leaves it to the right of any equal element, because it only shifts those strictly larger. So 2 equal elements never cross. Combined with being in place and adaptive, that makes it very practical.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Like arranging the cards in your hand