You just watched insertion sort: each number, from left to right, slides left past every bigger number into its place, so the left part is always sorted.

52819310467
the list you watched

Quick check

Quick check: In that run, which number had to slide past the most others?

Sorting a hand of cards#

Think about how you sort playing cards. You pick up one card at a time. You slide each new card left until the card before it is not bigger, and you put it there. The cards in your hand stay sorted the whole time.

Insertion sort does the same thing. The list has a sorted part on the left and an untouched part on the right. The next number is the key, the card you just picked up.

2581901234
sorted part is index 0 to 2, key is 1

Quick check

Quick check: The key is 1. Where does it end up, and how many numbers shift right?

The code#

Pick up the key, shift every bigger number in the sorted part one place right, drop the key in the gap. Index 0 alone is already sorted, so the loop starts at 1. Step through with x = 1, then slide x to 6.

Insertion sort, line by lineline 1
Try another x
  1. x = 1
  2. a = [5, 2, 4, x]
  3. for i in range(1, len(a)):
  4. key = a[i]
  5. j = i - 1
  6. while j>=0 and a[j]>key:
  7. a[j + 1] = a[j]
  8. j -= 1
  9. a[j + 1] = key
  10. print(a)

Variables

x
1 (just changed)

x is the last number. Slide it to try others.

Step 1 of 34

Quick check

Quick check: Right after the first shift, a is [5, 5, 4, 1]. The 2 is gone from the list. Is that a bug?

With x = 6, the last key is bigger than everything before it. The while test fails at once, nothing shifts, and 6 stays where it was. With x = 1, j walks all the way to -1, off the left edge, and 1 lands at index 0.

Quick check

Quick check: If a = [7], how many times does the for body run?

Best case and worst case#

A comparison is one check of a[j] > key. A shift is one copy to the right. Each key shifts once for every bigger number before it, but even with 0 shifts it still needs one comparison. Here are the counts for 5 numbers:

InputExampleShiftsTime
Already sorted[1, 2, 3, 4, 5]0O(n)
Random[3, 1, 5, 2, 4]4O(n²) on average
Reverse sorted[5, 4, 3, 2, 1]10O(n²)

On a sorted list, every key does one comparison and stops: n - 1 comparisons, so O(n). On a reverse sorted list, the key at index i shifts past all i numbers before it: 1 + 2 + ... + (n - 1) = n(n - 1)/2 shifts. In a random list about half of all pairs are out of order, so you get about half of that, roughly n²/4 shifts. Still O(n²).

Quick check

Quick check: 1,000 roll numbers arrive in reverse order. How many shifts does insertion sort make?

A nearly sorted list is almost as cheap as a sorted one. If every number is at most k places from its spot, each key shifts at most k times, so the work is at most about n × k.

Stable and in place#

A sort is stable if equal values keep their original order. Sort this class list by marks, and watch Asha and Ravi, who both scored 72.

Sorting by marks

class

namemarks
Asha72
Kiran65
Ravi72
Meena58
  • Same marks

Start. Asha and Ravi both have 72, Asha comes first.

Step 1 of 4

Asha is still before Ravi. The strict > in the while test means a number never moves past an equal one. For records like (name, marks), compare only the marks: a[j][1] > key[1].

Insertion sort is also in place. It sorts inside the same list and uses only a few variables (i, j, key) as extra space, which is O(1).

BubbleSelectionInsertion
Best timeO(n) with early stopO(n²)O(n)
Worst timeO(n²)O(n²)O(n²)
StableYesNoYes
Extra spaceO(1)O(1)O(1)

Where it is really used#

Insertion sort is slow on big random lists, but very fast on small or nearly sorted ones. It has very little overhead: no recursion, no extra list, and a short inner loop. That is why Python's sorted() and list.sort() use it inside Timsort. Timsort sorts short pieces of about 32 to 64 items with binary insertion sort (it finds the gap with binary search, then shifts), then joins the sorted pieces together. The merge sort step, after this one's problem, shows how that joining works.

SituationUse insertion sort?
Under about 50 itemsYes, often the fastest
Nearly sorted listYes, close to O(n)
Scores arriving one by one in a placement testYes, slide each into the sorted list
Large random listNo, O(n²)

One last check#

Quick check

Quick check: A list of 1,000 CGPAs is fully sorted, except two neighbours are swapped. About how much work does insertion sort do?

Next, play insertion sort on your own inputs in the visualizer, then write it yourself in Insertion Sort the Array.