1. Home
  2. Design & Analysis of Algorithms
  3. Insertion Sort

Insertion Sort

Sort the way you sort playing cards — pick up one card at a time and slide it into place. Fast on almost-sorted data.

Interactive 3DBeginner8 min readDAAUpdated

Drag to rotate · Right-drag to pan · Click, then scroll to zoom · Space play · Left arrowRight arrow step

What's happening

Insertion sort builds a sorted part on the left (cyan), one card at a time — exactly like sorting playing cards in your hand. At first, just a[0] counts as sorted.

Pseudocode

  1. procedure insertionSort(a):
  2. for i ← 1 to n − 1:
  3. key ← a[i]
  4. j ← i − 1
  5. while j ≥ 0 and a[j] > key:
  6. a[j + 1] ← a[j] // shift right
  7. j ← j − 1
  8. a[j + 1] ← key // drop key into the gap
Read this model as text · 47 steps

One run of the model above, written out step by step. Useful with a screen reader, on a slow connection, or for quick revision. The values may differ from the run on your screen.

  1. Insertion sort builds a sorted part on the left (cyan), one card at a time — exactly like sorting playing cards in your hand. At first, just a[0] counts as sorted.
  2. Pick up key = a[1] = 5 (it steps forward). Now find where it belongs in the sorted part on its left.
  3. a[0] = 12 > 5, so 12 must move right to make room.
  4. Shift 12 one place right (a[1] ← a[0]).
  5. Drop 5 into the gap at index 0. The first 2 elements are now sorted.
  6. Pick up key = a[2] = 12 (it steps forward). Now find where it belongs in the sorted part on its left.
  7. a[1] = 12 ≤ 12 — stop. The key goes right after it.
  8. Drop 12 into the gap at index 2. The first 3 elements are now sorted.
  9. Pick up key = a[3] = 8 (it steps forward). Now find where it belongs in the sorted part on its left.
  10. a[2] = 12 > 8, so 12 must move right to make room.
  11. Shift 12 one place right (a[3] ← a[2]).
  12. a[1] = 12 > 8, so 12 must move right to make room.
  13. Shift 12 one place right (a[2] ← a[1]).
  14. a[0] = 5 ≤ 8 — stop. The key goes right after it.
  15. Drop 8 into the gap at index 1. The first 4 elements are now sorted.
  16. Pick up key = a[4] = 3 (it steps forward). Now find where it belongs in the sorted part on its left.
  17. a[3] = 12 > 3, so 12 must move right to make room.
  18. Shift 12 one place right (a[4] ← a[3]).
  19. a[2] = 12 > 3, so 12 must move right to make room.
  20. Shift 12 one place right (a[3] ← a[2]).
  21. a[1] = 8 > 3, so 8 must move right to make room.
  22. Shift 8 one place right (a[2] ← a[1]).
  23. a[0] = 5 > 3, so 5 must move right to make room.
  24. Shift 5 one place right (a[1] ← a[0]).
  25. Drop 3 into the gap at index 0. The first 5 elements are now sorted.
  26. Pick up key = a[5] = 8 (it steps forward). Now find where it belongs in the sorted part on its left.
  27. a[4] = 12 > 8, so 12 must move right to make room.
  28. Shift 12 one place right (a[5] ← a[4]).
  29. a[3] = 12 > 8, so 12 must move right to make room.
  30. Shift 12 one place right (a[4] ← a[3]).
  31. a[2] = 8 ≤ 8 — stop. The key goes right after it.
  32. Drop 8 into the gap at index 3. The first 6 elements are now sorted.
  33. Pick up key = a[6] = 5 (it steps forward). Now find where it belongs in the sorted part on its left.
  34. a[5] = 12 > 5, so 12 must move right to make room.
  35. Shift 12 one place right (a[6] ← a[5]).
  36. a[4] = 12 > 5, so 12 must move right to make room.
  37. Shift 12 one place right (a[5] ← a[4]).
  38. a[3] = 8 > 5, so 8 must move right to make room.
  39. Shift 8 one place right (a[4] ← a[3]).
  40. a[2] = 8 > 5, so 8 must move right to make room.
  41. Shift 8 one place right (a[3] ← a[2]).
  42. a[1] = 5 ≤ 5 — stop. The key goes right after it.
  43. Drop 5 into the gap at index 2. The first 7 elements are now sorted.
  44. Pick up key = a[7] = 15 (it steps forward). Now find where it belongs in the sorted part on its left.
  45. a[6] = 12 ≤ 15 — stop. The key goes right after it.
  46. Drop 15 into the gap at index 7. The first 8 elements are now sorted.
  47. Sorted with 18 comparisons and 13 shifts. Worst case (reversed) is O(n²), but on almost sorted data insertion sort is nearly O(n) — try Already sorted!

Try this in the 3D model

  • Watch the cyan "sorted part" grow from the left by one bar each round.
  • Load Already sorted. How many shifts happen? That's the best case.
  • Load Reversed and count the shifts. Every bar has to travel all the way left.
  • Compare the number of comparisons with Bubble Sort on the same numbers.

The idea

Think about how you sort a hand of playing cards. You pick up cards one at a time, and each new card gets inserted into the correct place among the cards you’re already holding. The cards in your hand are always sorted.

Insertion sort does exactly this:

  1. Treat the first element as a sorted list of length 1.
  2. Take the next element — the key.
  3. Shift every bigger element in the sorted part one place right.
  4. Drop the key into the gap.
  5. Repeat until every element has been inserted.

In the 3D model, the key steps forward out of the row, the bigger bars slide right one by one, and the key drops into the hole.

Step by step example

Sorting [5, 2, 4, 6, 1, 3]:

i key sorted part after inserting
1 2 [2, 5] 4 6 1 3
2 4 [2, 4, 5] 6 1 3
3 6 [2, 4, 5, 6] 1 3 (no shift needed)
4 1 [1, 2, 4, 5, 6] 3 (1 travels all the way)
5 3 [1, 2, 3, 4, 5, 6]

Code

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]          # shift right
            j -= 1
        a[j + 1] = key               # drop into the gap
    return a

print(insertion_sort([5, 2, 4, 6, 1, 3]))   # [1, 2, 3, 4, 5, 6]
#include <iostream>
#include <vector>
using namespace std;

void insertionSort(vector<int>& a) {
    for (int i = 1; i < (int)a.size(); i++) {
        int key = a[i], j = i - 1;
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
    }
}

int main() {
    vector<int> a = {5, 2, 4, 6, 1, 3};
    insertionSort(a);
    for (int x : a) cout << x << " ";   // 1 2 3 4 5 6
}

Analysis

  • Best case — O(n): the array is already sorted, so each key is compared once and never moves.
  • Worst case — O(n²): the array is reversed, so key number i shifts past all i sorted elements: 1 + 2 + … + (n−1) = n(n−1)/2 moves.
  • Space — O(1): it sorts in place.

It is stable, in-place and adaptive (it gets faster the more sorted the input already is) and online — it can sort data as it arrives.

Insertion sort vs bubble sort vs selection sort

Insertion Bubble Selection
Worst case O(n²) O(n²) O(n²)
Best case O(n) O(n) with early exit O(n²)
Swaps / writes Many shifts Many swaps At most n−1 swaps
Stable ✅ ✅ ❌
In practice Fastest of the three Slowest Few writes

Where is it used?

Insertion sort is the go-to algorithm for small or nearly sorted arrays. Real libraries take advantage of this: Timsort (Python’s sorted, Java’s object sort) and introsort (C++ std::sort) both switch to insertion sort for pieces smaller than about 16–64 elements.

Common mistakes

  • Writing a[j] >= key — it still sorts, but it is no longer stable.
  • Forgetting j >= 0 in the loop condition (index −1 crash).
  • Placing the key at a[j] instead of a[j + 1].

Complexity at a glance

Case / operationTimeWhy
Best case (already sorted)O(n)One comparison per element, no shifts.
Average caseO(n²)About n²/4 shifts.
Worst case (reversed)O(n²)Every key shifts past all sorted elements.
Extra spaceO(1)

Quick check

Test yourself — pick an answer to see if you got it.

1. After the outer loop has run for i = 1, 2 and 3, what is guaranteed?

2. Why is insertion sort fast on nearly sorted data?

3. Is insertion sort stable?

4. Which real sorting algorithm uses insertion sort for small pieces?

Saved in this browser.
Spotted a mistake or a bug in the 3D model?

Report a mistake

in Insertion Sort. Thank you — every report makes the lesson better for the next reader.

We'll also include a link to the step of the 3D model you're on and your browser type, so we can reproduce it.