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.
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.
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.
x- x = 1
- a = [5, 2, 4, x]
- 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
- print(a)
Variables
- x
- 1 (just changed)
x is the last number. Slide it to try others.
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:
| Input | Example | Shifts | Time |
|---|---|---|---|
| Already sorted | [1, 2, 3, 4, 5] | 0 | O(n) |
| Random | [3, 1, 5, 2, 4] | 4 | O(n²) on average |
| Reverse sorted | [5, 4, 3, 2, 1] | 10 | O(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.
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).
| Bubble | Selection | Insertion | |
|---|---|---|---|
| Best time | O(n) with early stop | O(n²) | O(n) |
| Worst time | O(n²) | O(n²) | O(n²) |
| Stable | Yes | No | Yes |
| Extra space | O(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.
| Situation | Use insertion sort? |
|---|---|
| Under about 50 items | Yes, often the fastest |
| Nearly sorted list | Yes, close to O(n) |
| Scores arriving one by one in a placement test | Yes, slide each into the sorted list |
| Large random list | No, 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.