Skip to main content

Sorting by Insertion

11 min readRead first: The Sorting Problem · Complexity of Loops

Insertion sort is the method most people use, without thinking, to sort a hand of cards: take the cards one by one and insert each one into its place among the cards already sorted. It is a quadratic algorithm, like bubble sort, but it is much better in practice: it performs fewer comparisons and moves, and it is extremely fast on data that is already almost sorted. For this reason, it is used inside many professional sorting algorithms.

What you will learn in this lesson
  • How direct insertion works, and how to trace it.
  • The exact number of comparisons and moves in the best, worst and average cases, and their relation with inversions.
  • Why insertion sort is adaptive, and why that makes it valuable in practice.
  • Binary insertion, which reduces the comparisons, and why it is still quadratic.

The Idea​

The vector is divided into two "virtual" parts: a sorted sequence on the left and an unsorted sequence on the right. Initially, the sorted part contains only the first element (a single element is always sorted).

In each step, we take the first element of the unsorted sequence and insert it into its corresponding place in the sorted sequence. To make room, the elements of the sorted part that are greater than it are shifted one position to the right. After n−1n - 1 steps, the sorted part covers the whole vector.

public void sort(int[] elements) {
for (int i = 1; i < elements.length; i++) {
int key = elements[i]; // first element of the unsorted part
int j = i - 1;
while (j >= 0 && key < elements[j]) { // shift the greater elements to the right
elements[j + 1] = elements[j];
j--;
}
elements[j + 1] = key; // insert the element in the gap
}
}

The element being inserted is stored in a variable (called key here, and pivot in some versions of the code) because its position will be overwritten by the shifts. Note that shifting an element requires one assignment, while a swap requires three: insertion sort moves data more cheaply than bubble sort.

Trace​

With the initial vector 4 5 6 1 3 2 7 8:

StepElement insertedSorted part | unsorted partShifts
154 5 | 6 1 3 2 7 80
264 5 6 | 1 3 2 7 80
311 4 5 6 | 3 2 7 83
431 3 4 5 6 | 2 7 83
521 2 3 4 5 6 | 7 84
671 2 3 4 5 6 7 | 80
781 2 3 4 5 6 7 80

Elements that are already greater than everything in the sorted part (5, 6, 7 and 8) are inserted with a single comparison and no shift. The total number of shifts is 3+3+4=103 + 3 + 4 = 10: exactly the number of inversions of the initial vector, as we will see now.

ProofInsertion sort is correct
Step 5 of insertion sort: the 2 is inserted into the sorted part 1 3 4 5 613456782key = 2 (saved before shifting)6, 5, 4 and 3 are greater than 2: each one shifts one place rightbefore12345678aftersorted partunsorted part
Step 5 of the trace: the key 2 is saved, the greater elements of the sorted part (6, 5, 4 and 3) shift one place to the right, and the 2 drops into the gap. The sorted part grows by one element.

Analysis​

When inserting the element at position ii, the inner loop compares it with the elements of the sorted part, from right to left, until it finds one that is not greater (or reaches the beginning). Each element greater than key is shifted once. Therefore, the number of shifts in step ii is the number of elements before position ii that are greater than key: exactly the number of inversions in which key is the second element. Summing over all steps:

The total number of shifts performed by insertion sort is exactly the number of inversions of the input.

And each step performs one comparison per shift, plus (usually) one more comparison that stops the loop.

🔍 Detailed count for each case
  • Best case (already sorted): each element is compared once with the previous element, which is smaller, and the loop stops immediately. C(n)=n−1C(n) = n - 1 comparisons and 0 shifts. In addition, each step saves and restores key: 2(n−1)2(n-1) assignments, which are not shifts of other elements.
  • Worst case (reverse order): the element at position ii is smaller than all the ii elements before it, so it is compared with all of them and all of them are shifted: ∑i=1n−1i=n(n−1)2\sum_{i=1}^{n-1} i = \frac{n(n-1)}{2} comparisons and n(n−1)2\frac{n(n-1)}{2} shifts. With n=5n = 5 and the input 5 4 3 2 1, steps 1 to 4 make 1,2,3,41, 2, 3, 4 comparisons and shifts, 10 in total: the same staircase as in bubble and selection sort, climbed upwards.
  • Average case (random order): on average, each element is greater than half of the previous ones, so the number of shifts is the expected number of inversions, n(n−1)4\frac{n(n-1)}{4}. The comparisons are the shifts plus the one comparison that stops each step (the one that finds an element that is not greater). That extra comparison is missing only when the element travels all the way to the front, because then the loop ends by reaching position 0. So C(n)C(n) = shifts + (n−1)(n - 1) − (times an element goes to the front). On average an element goes to the front only Hn−1H_n - 1 times, where Hn=1+12+⋯+1n≈ln⁡nH_n = 1 + \frac{1}{2} + \cdots + \frac{1}{n} \approx \ln n, which gives C(n)=n(n−1)4+n−HnC(n) = \frac{n(n-1)}{4} + n - H_n. In our measurement with n=1,000n = 1{,}000 the difference between comparisons and shifts was 997 = 999 − 2. For large nn the extra n−Hnn - H_n hardly matters: both counts are about n24\frac{n^2}{4}.
CaseComparisons C(n)C(n)Shifts M(n)M(n)Complexity
Best (sorted)n−1n - 100O(n)O(n)
Worst (reverse order)n(n−1)2\frac{n(n-1)}{2}n(n−1)2\frac{n(n-1)}{2}O(n2)O(n^2)
Average (random)n(n−1)4+n−Hn≈n24\frac{n(n-1)}{4} + n - H_n \approx \frac{n^2}{4}n(n−1)4\frac{n(n-1)}{4}O(n2)O(n^2)

We verified these values by instrumenting the algorithm with n=1,000n = 1{,}000: 999 comparisons for sorted data, 499,500 comparisons and shifts for reverse data, and 252,985 comparisons and 251,988 shifts for random data.

Compared with bubble sort, insertion sort performs half the comparisons on average (n24\frac{n^2}{4} instead of n22\frac{n^2}{2}), and its moves are shifts (one assignment) instead of swaps (three assignments). It is stable (an element stops as soon as it finds one that is not greater, so it never jumps over an equal element) and in place.


Insertion Sort Is Adaptive​

Since the work is proportional to the number of inversions, the cost of insertion sort is, more precisely,

T(n)=O(n+I)T(n) = O(n + I)

where II is the number of inversions of the input. For an almost sorted input, with only a few elements out of place, II is small and the algorithm is practically linear. This is much stronger than the adaptivity of bubble sort with a sentinel, which, as we saw, can still be quadratic when a single element is misplaced (the "turtle" problem). For insertion sort, a single misplaced element costs at most nn additional shifts, wherever it is.

This property makes insertion sort very valuable in practice:

  • it is the best choice for small arrays, thanks to its very low overhead;
  • it is ideal to maintain a sorted collection to which elements are added one by one;
  • many efficient algorithms use it as a component: Quicksort and Mergesort implementations often switch to insertion sort for small subarrays, and the TimSort algorithm used by Java to sort objects relies on it to process short runs.
🧠 Checkpoint: Almost sorted data

Question: A vector of n=1,000,000n = 1{,}000{,}000 elements is sorted, except that 10 random elements have been changed to random values. Approximately how much work does insertion sort do? And bubble sort with a sentinel?

Answer: Each of the 10 misplaced elements creates, at most, about nn inversions, so I≤10nI \le 10n and insertion sort performs at most around 10710^7 shifts plus 10610^6 comparisons: a few hundredths of a second. Bubble sort with a sentinel depends on where the misplaced elements are: if one of them must move a long way to the right (a "turtle"), it may need a number of passes proportional to nn, each with up to nn comparisons: hundreds of billions of operations, which means hours instead of milliseconds.


Binary Insertion​

In each step, the element is inserted into a sorted sequence. We can therefore find its position with binary search instead of comparing it with the elements one by one:

public void sort(int[] elements) {
for (int i = 1; i < elements.length; i++) {
int key = elements[i];
int left = 0;
int right = i - 1;
while (left <= right) { // binary search of the insertion point
int center = left + (right - left) / 2;
if (key < elements[center])
right = center - 1;
else
left = center + 1; // equal elements: insert after them (stable)
}
for (int j = i - 1; j >= left; j--) // shift to make room
elements[j + 1] = elements[j];
elements[left] = key;
}
}

The number of comparisons drops to about log⁡2i\log_2 i per step, that is, about nlog⁡2nn \log_2 n in total, whatever the input. But the number of shifts does not change: the element must still be moved to its place, and all the greater elements must still move one position. In the worst and average cases, the shifts are still O(n2)O(n^2), so binary insertion is still quadratic.

It is advantageous when comparisons are expensive (long strings, complex objects) compared with moves. Notice also that it is less adaptive: on sorted data, it performs about nlog⁡2nn \log_2 n comparisons instead of n−1n - 1. The else branch, which moves left to the right when the keys are equal, keeps the algorithm stable.


Measurements​

Times in milliseconds, without optimization (-Xint), with the course implementations:

AlgorithmnnSortedRandomReverse
Direct insertion4,0000.180157
8,0000.2329670
Binary insertion4,0001.152102
8,0002.4227430
Bubble (for comparison)8,0005421,1321,592
  • On sorted data, direct insertion is practically instantaneous (linear time), while binary insertion is slower, because it always performs its binary searches.
  • On random and reverse data, both are quadratic (the times multiply by about 4 when nn doubles), and the reverse case costs about twice the random one, matching the formulas (n22\frac{n^2}{2} versus n24\frac{n^2}{4} shifts).
  • Direct insertion is 3 to 4 times faster than bubble sort on random data, and binary insertion is faster still, thanks to its fewer comparisons.
Common mistakes
  • Swapping at every step instead of shifting. Shift the larger elements and write the inserted element once.
  • Not stopping the inner loop when the element is in place. That loses the linear best case on sorted data.
  • Using >= instead of > when shifting. Equal elements would jump over each other and the sort would no longer be stable.

Summary​

  • Insertion sort keeps a sorted part on the left and inserts the next element into it, shifting the greater elements.
  • The number of shifts equals the number of inversions: T(n)=O(n+I)T(n) = O(n + I). Best case O(n)O(n); worst and average cases O(n2)O(n^2).
  • It performs about half the comparisons of bubble sort, and cheaper moves. It is stable, in place and adaptive.
  • It is the best simple algorithm in practice, the best choice for small or almost sorted arrays, and a building block of efficient hybrid algorithms.
  • Binary insertion reduces the comparisons to O(nlog⁡n)O(n \log n), but the moves remain O(n2)O(n^2).

Practice​

  • ✍️ Trace it. Sort 5 6 1 3 9 8 7 4 2 by hand with direct insertion, showing the sorted and unsorted parts after each step and the number of shifts. Check that the total number of shifts equals the number of inversions.
  • 🔁 Sort in decreasing order. Which single change in the code sorts the vector in decreasing order? Is the result still stable?
  • 💻 Measure. Measure direct insertion with sorted, reverse and random data, without optimization, and compare the ratios between consecutive times with those of bubble sort (lab session 2).
  • 🧪 Almost sorted. Generate a sorted vector of 100,000 elements, change kk random positions, and measure insertion sort for k=0,10,100,1,000k = 0, 10, 100, 1{,}000. How does the time depend on kk?
  • ⚖️ Expensive comparisons. Sort an array of long strings with direct insertion and with binary insertion, counting comparisons. When does binary insertion pay off?
Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.