Skip to content

11.4   Insertion sort

Insertion sort is a simple algorithm that works much like arranging a hand of playing cards.

Choose an element from the unsorted range, compare it with elements in the sorted range to its left one at a time, and insert it at the correct position.

Figure 11-6 shows how to insert an element into an array. Call the element base. Shift all elements from the target index up to, but excluding, base one position to the right. Then write base at the target index.

Figure 11-6   A single insertion

Description of Figure 11-6: Inserting one element: save, shift right, and write back

Save the final 3, copy 5 and 4 one place to the right in turn, then write 3 at index 3.

The input is nums = [1, 1, 2, 4, 5, 3] (indices 0 through 5). The first five elements [1, 1, 2, 4, 5] are sorted. Insert 3 at the correct position in the sorted range of nums: index 3, between 2 and 4.

Save the final 3 in base so that shifting right does not overwrite it. In turn, copy 5 and 4, both greater than 3, one place to the right. These assignments temporarily leave two 5s or two 4s in the array.

When you reach the 2 at index 2, stop shifting elements to the right and write the value saved in base to index 3. The top of the figure shows the original input for reference. Below it, four rows show the successive states of the array from top to bottom. The first of these rows still shows the initial array. The four rows in the table below follow the same order.

Array changes during one insertion
ActionArraybase
Save the final 3 (base = nums[5])[1, 1, 2, 4, 5, 3]3
Copy 5 to index 5 (nums[5] = nums[4])[1, 1, 2, 4, 5, 5]3
Copy 4 to index 4 (nums[4] = nums[3])[1, 1, 2, 4, 4, 5]3
Write 3 to index 3 (nums[3] = base)[1, 1, 2, 3, 4, 5]3

Both right shifts are copy assignments. The value to insert, 3, stays in base until it is written to the position cleared for insertion.

11.4.1   How the algorithm works

Figure 11-7 shows the full insertion sort procedure.

  1. Initially, the first element of the array is already sorted.
  2. Choose the second element as base and insert it at the correct position. The first two elements are now sorted.
  3. Choose the third element as base and insert it at the correct position. The first three elements are now sorted.
  4. Continue in the same way. In the final pass, choose the last element as base and insert it at the correct position. All elements are now sorted.

Figure 11-7   Insertion sort procedure

Description of Figure 11-7: Insertion sort pass by pass

Each pass inserts the next element on the right into the sorted prefix, extending it by one.

Initially nums = [4, 1, 3, 1, 5, 2], with indices 0 through 5. The single-element range holding the first element, 4, is already sorted. The initial sorted range is therefore [0, 0].

Each pass takes the element immediately to the right of the sorted prefix as base, shifts larger elements right, and writes base into the position that opens up.

Only the order within the prefix is guaranteed. Its elements may still shift right when smaller elements are inserted later.

Pass 3 inserts the second 1. Shifting stops at the equal first 1, preserving their original order. The 5 in pass 4 needs no move, but the prefix still grows. Pass 5 inserts 2 to finish sorting.

Array states by insertion sort pass
StageArraySorted rangeValue to insert next
Initial[4, 1, 3, 1, 5, 2][0, 0]1
After pass 1[1, 4, 3, 1, 5, 2][0, 1]3
After pass 2[1, 3, 4, 1, 5, 2][0, 2]1
After pass 3[1, 1, 3, 4, 5, 2][0, 3]5
After pass 4[1, 1, 3, 4, 5, 2][0, 4]2
After pass 5[1, 1, 2, 3, 4, 5][0, 5]None, sorting complete

After five passes, the sorted prefix covers the whole array and the two 1s remain in their original order.

Here is an implementation:

insertion_sort.py
def insertion_sort(nums: list[int]):
    """Insertion sort"""
    # Outer loop: the sorted range is [0, i-1]
    for i in range(1, len(nums)):
        base = nums[i]
        j = i - 1
        # Inner loop: insert base at the correct position in the sorted range [0, i-1]
        while j >= 0 and nums[j] > base:
            nums[j + 1] = nums[j]  # Shift nums[j] one position to the right
            j -= 1
        nums[j + 1] = base  # Place base at the correct position
insertion_sort.cpp
/* Insertion sort */
void insertionSort(vector<int> &nums) {
    // Outer loop: the sorted range is [0, i-1]
    for (int i = 1; i < nums.size(); i++) {
        int base = nums[i], j = i - 1;
        // Inner loop: insert base at the correct position in the sorted range [0, i-1]
        while (j >= 0 && nums[j] > base) {
            nums[j + 1] = nums[j]; // Shift nums[j] one position to the right
            j--;
        }
        nums[j + 1] = base; // Place base at the correct position
    }
}
insertion_sort.java
/* Insertion sort */
void insertionSort(int[] nums) {
    // Outer loop: the sorted range is [0, i-1]
    for (int i = 1; i < nums.length; i++) {
        int base = nums[i], j = i - 1;
        // Inner loop: insert base at the correct position in the sorted range [0, i-1]
        while (j >= 0 && nums[j] > base) {
            nums[j + 1] = nums[j]; // Shift nums[j] one position to the right
            j--;
        }
        nums[j + 1] = base;        // Place base at the correct position
    }
}
insertion_sort.cs
/* Insertion sort */
void InsertionSort(int[] nums) {
    // Outer loop: the sorted range is [0, i-1]
    for (int i = 1; i < nums.Length; i++) {
        int bas = nums[i], j = i - 1;
        // Inner loop: insert base at the correct position in the sorted range [0, i-1]
        while (j >= 0 && nums[j] > bas) {
            nums[j + 1] = nums[j]; // Shift nums[j] one position to the right
            j--;
        }
        nums[j + 1] = bas;         // Place base at the correct position
    }
}
insertion_sort.go
/* Insertion sort */
func insertionSort(nums []int) {
    // Outer loop: the sorted range is [0, i-1]
    for i := 1; i < len(nums); i++ {
        base := nums[i]
        j := i - 1
        // Inner loop: insert base at the correct position in the sorted range [0, i-1]
        for j >= 0 && nums[j] > base {
            nums[j+1] = nums[j] // Shift nums[j] one position to the right
            j--
        }
        nums[j+1] = base // Place base at the correct position
    }
}
insertion_sort.swift
/* Insertion sort */
func insertionSort(nums: inout [Int]) {
    // Outer loop: the sorted range is [0, i-1]
    for i in nums.indices.dropFirst() {
        let base = nums[i]
        var j = i - 1
        // Inner loop: insert base at the correct position in the sorted range [0, i-1]
        while j >= 0, nums[j] > base {
            nums[j + 1] = nums[j] // Shift nums[j] one position to the right
            j -= 1
        }
        nums[j + 1] = base // Place base at the correct position
    }
}
insertion_sort.js
/* Insertion sort */
function insertionSort(nums) {
    // Outer loop: the sorted range is [0, i-1]
    for (let i = 1; i < nums.length; i++) {
        let base = nums[i],
            j = i - 1;
        // Inner loop: insert base at the correct position in the sorted range [0, i-1]
        while (j >= 0 && nums[j] > base) {
            nums[j + 1] = nums[j]; // Shift nums[j] one position to the right
            j--;
        }
        nums[j + 1] = base; // Place base at the correct position
    }
}
insertion_sort.ts
/* Insertion sort */
function insertionSort(nums: number[]): void {
    // Outer loop: the sorted range is [0, i-1]
    for (let i = 1; i < nums.length; i++) {
        const base = nums[i];
        let j = i - 1;
        // Inner loop: insert base at the correct position in the sorted range [0, i-1]
        while (j >= 0 && nums[j] > base) {
            nums[j + 1] = nums[j]; // Shift nums[j] one position to the right
            j--;
        }
        nums[j + 1] = base; // Place base at the correct position
    }
}
insertion_sort.dart
/* Insertion sort */
void insertionSort(List<int> nums) {
  // Outer loop: the sorted range is [0, i-1]
  for (int i = 1; i < nums.length; i++) {
    int base = nums[i], j = i - 1;
    // Inner loop: insert base at the correct position in the sorted range [0, i-1]
    while (j >= 0 && nums[j] > base) {
      nums[j + 1] = nums[j]; // Shift nums[j] one position to the right
      j--;
    }
    nums[j + 1] = base; // Place base at the correct position
  }
}
insertion_sort.rs
/* Insertion sort */
fn insertion_sort(nums: &mut [i32]) {
    // Outer loop: the sorted range is [0, i-1]
    for i in 1..nums.len() {
        let (base, mut j) = (nums[i], (i - 1) as i32);
        // Inner loop: insert base at the correct position in the sorted range [0, i-1]
        while j >= 0 && nums[j as usize] > base {
            nums[(j + 1) as usize] = nums[j as usize]; // Shift nums[j] one position to the right
            j -= 1;
        }
        nums[(j + 1) as usize] = base; // Place base at the correct position
    }
}
insertion_sort.c
/* Insertion sort */
void insertionSort(int nums[], int size) {
    // Outer loop: the sorted range is [0, i-1]
    for (int i = 1; i < size; i++) {
        int base = nums[i], j = i - 1;
        // Inner loop: insert base at the correct position in the sorted range [0, i-1]
        while (j >= 0 && nums[j] > base) {
            // Shift nums[j] one position to the right
            nums[j + 1] = nums[j];
            j--;
        }
        // Place base at the correct position
        nums[j + 1] = base;
    }
}
insertion_sort.kt
/* Insertion sort */
fun insertionSort(nums: IntArray) {
    //Outer loop: the number of sorted elements runs from 1 through n
    for (i in nums.indices) {
        val base = nums[i]
        var j = i - 1
        // Inner loop: insert base at the correct position in the sorted range [0, i-1]
        while (j >= 0 && nums[j] > base) {
            nums[j + 1] = nums[j] // Shift nums[j] one position to the right
            j--
        }
        nums[j + 1] = base        // Place base at the correct position
    }
}
insertion_sort.rb
### Insertion sort ###
def insertion_sort(nums)
  n = nums.length
  # Outer loop: the sorted range is [0, i-1]
  for i in 1...n
    base = nums[i]
    j = i - 1
    # Inner loop: insert base at the correct position in the sorted range [0, i-1]
    while j >= 0 && nums[j] > base
      nums[j + 1] = nums[j] # Shift nums[j] one position to the right
      j -= 1
    end
    nums[j + 1] = base # Place base at the correct position
  end
end
Visualize execution

11.4.2   Algorithm properties

  • Time complexity: \(O(n^2)\), adaptive. In the worst case, the insertions require \(n - 1\), \(n-2\), \(\dots\), \(2\), and \(1\) iterations, respectively, adding up to \((n - 1) n / 2\). The time complexity is therefore \(O(n^2)\). On ordered data, the insertion loop stops early. A fully sorted array achieves the best-case time complexity of \(O(n)\).
  • Space complexity: \(O(1)\), in-place. The two indices \(i\) and \(j\) use a constant amount of extra space.
  • Stable. Each insertion places the new element to the right of any equal elements, preserving their relative order.

11.4.3   Advantages of insertion sort

Insertion sort has time complexity \(O(n^2)\), whereas quicksort, which we will study shortly, has time complexity \(O(n \log n)\). Despite its higher time complexity, insertion sort is usually faster on small inputs.

This is similar to the trade-off between linear and binary search. Algorithms such as quicksort achieve \(O(n \log n)\) time using divide and conquer, which often involves more elementary operations per round. For small inputs, the values of \(n^2\) and \(n \log n\) are close. The number of operations per round then matters more than the asymptotic growth rate.

In fact, the built-in sorts in many languages, including Java, use insertion sort. The general idea is to use a divide-and-conquer sort such as quicksort for long arrays and insertion sort directly for short arrays.

Bubble sort, selection sort, and insertion sort all have time complexity \(O(n^2)\). In practice, however, insertion sort is used far more often than either bubble sort or selection sort, mainly for the following reasons.

  • Bubble sort moves elements by swapping them. A swap with a temporary variable takes three elementary operations. Insertion sort shifts an element with a single assignment. As a result, bubble sort usually requires more work than insertion sort.
  • Selection sort takes \(O(n^2)\) time in all cases. On partially sorted data, insertion sort is usually more efficient than selection sort.
  • Selection sort is unstable, so it cannot be used for successive sorts by different keys that must preserve earlier ordering.
Share your thoughts, questions, or suggestions in the comments.