Algorithm · Sorting and selection · O(n²) worst, O(n) sorted

Insertion sort

Grow a sorted prefix by inserting the next element into place. Stable, in place, O(n²) worst case and very fast on small or nearly sorted input.

The full derivation, edge cases and exercises are in the lesson Correctness: loop invariants and edge cases. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

The prefix a[0 … i − 1] is always sorted. To add a[i], lift it out, shift larger elements one slot right, and drop it into the gap. On nearly sorted data each element moves only a few slots, which is why library sorts switch to insertion sort for small subarrays.

Steps

  1. For i from 1 to n − 1, hold key = a[i].
  2. Shift every element of the sorted prefix that is greater than key one slot right.
  3. Write key into the gap.

Invariants

What holds at every step; the correctness argument rests on these.

  • Before step i, a[0 … i − 1] holds the original first i elements in sorted order.
  • Only strictly greater elements shift past the key, so the sort is stable.

Complexity

Insertion sort complexity
CaseTimeExtra spaceNotes
Best case (sorted)O(n)O(1)
Average / worstO(n²)O(1)Shifts = number of inversions.

When to use it

Use it when

  • Small arrays (tens of elements) or data that is almost sorted already.
  • Elements arrive one at a time and the sorted prefix must stay sorted.

Avoid it when

  • Large unsorted arrays: use an O(n log n) sort.

Step through it

The interactive lab for insertion sort: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

Insertion sort in four languages, checked against the merge sort fixture (which also verifies stability) and random inputs compared with the language's stable built-in sort.

namespace Bekadan.Dsa.Examples.Sorting;
 
/// <summary>
/// Bubble sort (with the early exit) and insertion sort. Both are stable and in
/// place: Θ(n²) comparisons in the worst case, Θ(n) on already sorted input.
/// </summary>
public static class ElementarySorts
{
    public static void BubbleSort<T>(T[] items, Comparison<T> compare)
    {
        for (int end = items.Length - 1; end > 0; end--)
        {
            bool swapped = false;
            for (int i = 0; i < end; i++)
            {
                if (compare(items[i + 1], items[i]) < 0) // strictly smaller: equal items never swap (stable)
                {
                    (items[i], items[i + 1]) = (items[i + 1], items[i]);
                    swapped = true;
                }
            }
            if (!swapped)
                break; // no swap in a whole pass: already sorted
        }
    }
 
    public static void InsertionSort<T>(T[] items, Comparison<T> compare)
    {
        for (int i = 1; i < items.Length; i++)
        {
            T key = items[i];
            int j = i - 1;
            while (j >= 0 && compare(items[j], key) > 0) // strictly greater: equal items stay in order (stable)
            {
                items[j + 1] = items[j];
                j--;
            }
            items[j + 1] = key;
        }
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Sorting/ElementarySorts.cs

"""Bubble sort (with the early exit) and insertion sort.
 
Both are stable and in place: Θ(n²) comparisons in the worst case, Θ(n) on
already sorted input.
"""
 
from collections.abc import Callable
from typing import Any
 
 
def _identity(item: Any) -> Any:
    return item
 
 
def bubble_sort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
    for end in range(len(items) - 1, 0, -1):
        swapped = False
        for i in range(end):
            if key(items[i + 1]) < key(items[i]):  # strictly smaller: equal items never swap (stable)
                items[i], items[i + 1] = items[i + 1], items[i]
                swapped = True
        if not swapped:
            break  # no swap in a whole pass: already sorted
 
 
def insertion_sort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
    for i in range(1, len(items)):
        current = items[i]
        j = i - 1
        while j >= 0 and key(items[j]) > key(current):  # strictly greater: equal items stay in order (stable)
            items[j + 1] = items[j]
            j -= 1
        items[j + 1] = current

Tested on CPython 3.14.0 · examples/python/dsa_examples/elementary_sorts.py

package dev.bekadan.dsa.sorting;
 
import java.util.Comparator;
 
/**
 * Bubble sort (with the early exit) and insertion sort. Both are stable and in
 * place: Θ(n²) comparisons in the worst case, Θ(n) on already sorted input.
 */
public final class ElementarySorts {
    private ElementarySorts() {
    }
 
    public static <T> void bubbleSort(T[] items, Comparator<? super T> comparator) {
        for (int end = items.length - 1; end > 0; end--) {
            boolean swapped = false;
            for (int i = 0; i < end; i++) {
                if (comparator.compare(items[i + 1], items[i]) < 0) { // strictly smaller: equal items never swap (stable)
                    T tmp = items[i];
                    items[i] = items[i + 1];
                    items[i + 1] = tmp;
                    swapped = true;
                }
            }
            if (!swapped) {
                break; // no swap in a whole pass: already sorted
            }
        }
    }
 
    public static <T> void insertionSort(T[] items, Comparator<? super T> comparator) {
        for (int i = 1; i < items.length; i++) {
            T key = items[i];
            int j = i - 1;
            while (j >= 0 && comparator.compare(items[j], key) > 0) { // strictly greater: equal items stay in order
                items[j + 1] = items[j];
                j--;
            }
            items[j + 1] = key;
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/sorting/ElementarySorts.java

#pragma once
 
#include <cstddef>
#include <functional>
#include <span>
#include <utility>
 
namespace bekadan::dsa {
 
// Bubble sort (with the early exit) and insertion sort. Both are stable and in
// place: Θ(n²) comparisons in the worst case, Θ(n) on already sorted input.
 
template <typename T, typename Less = std::less<>>
void bubble_sort(std::span<T> items, Less less = {}) {
    for (std::size_t end = items.size(); end > 1; --end) {
        bool swapped = false;
        for (std::size_t i = 0; i + 1 < end; ++i) {
            if (less(items[i + 1], items[i])) {  // strictly smaller: equal items never swap (stable)
                std::swap(items[i], items[i + 1]);
                swapped = true;
            }
        }
        if (!swapped)
            break;  // no swap in a whole pass: already sorted
    }
}
 
template <typename T, typename Less = std::less<>>
void insertion_sort(std::span<T> items, Less less = {}) {
    for (std::size_t i = 1; i < items.size(); ++i) {
        T key = std::move(items[i]);
        std::size_t j = i;  // the gap is at j; compare with items[j - 1]
        while (j > 0 && less(key, items[j - 1])) {  // strictly greater on the left: equal items stay in order
            items[j] = std::move(items[j - 1]);
            --j;
        }
        items[j] = std::move(key);
    }
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/elementary_sorts.hpp

Learn more

Data structures it uses

Comparisons

  • Bubble sort vs insertion sort· Two quadratic, stable, in-place sorts on one array, with merge sort as an optional third lane. Counts are compared, not timed.

Problems, patterns and exercises

References