beginnersorting

Insertion Sort

Insertion Sort

Insertion sort works the way you might sort a hand of playing cards. You pick up one card at a time and insert it into the correct position among the cards you've already sorted. It's intuitive, simple to implement, and surprisingly efficient for small or nearly sorted datasets.

How It Works

  1. Start with the second element (index 1) — the first element is already "sorted"
  2. Compare the current element with the elements to its left
  3. Shift all larger elements one position to the right
  4. Insert the current element into the gap created
  5. Repeat for every remaining element until the entire array is sorted

Step-by-Step Example

Given the array [5, 2, 4, 6, 1, 3]:

  • Pass 1: Pick 2. Compare with 5, shift 5 right. Insert 2 → [2, 5, 4, 6, 1, 3]
  • Pass 2: Pick 4. Compare with 5, shift 5 right. 2 < 4, stop. Insert 4 → [2, 4, 5, 6, 1, 3]
  • Pass 3: Pick 6. 5 < 6, no shift needed → [2, 4, 5, 6, 1, 3]
  • Pass 4: Pick 1. Shift 6, 5, 4, 2 all right. Insert 1 → [1, 2, 4, 5, 6, 3]
  • Pass 5: Pick 3. Shift 6, 5, 4 right. Insert 3 → [1, 2, 3, 4, 5, 6]

Code Snippet

def insertion_sort(numbers: list[int]) -> list[int]:
    """Sort by inserting each element into its correct position."""
    for i in range(1, len(numbers)):
        current_value = numbers[i]
        insert_position = i - 1

        # Shift elements that are greater than current_value to the right
        while insert_position >= 0 and numbers[insert_position] > current_value:
            numbers[insert_position + 1] = numbers[insert_position]
            insert_position -= 1

        # Place the current value in the correct position
        numbers[insert_position + 1] = current_value

    return numbers

Complexity Analysis

Time Complexity: O(n²)

  • Best case — O(n): When the array is already sorted, the inner loop never executes. Each element is compared once with its predecessor, giving exactly n-1 comparisons.
  • Worst case — O(n²): When the array is reverse-sorted, every element must be compared against all previously sorted elements, resulting in 1 + 2 + 3 + ... + (n-1) = n(n-1)/2 comparisons.
  • Average case — O(n²): On average, each element is compared against half of the sorted portion.

Space Complexity: O(1)

Insertion sort is an in-place algorithm. It only uses a constant amount of extra memory for the current_value variable and the index pointer, regardless of input size.

When to Use Insertion Sort

  • Small arrays (n < 50): The low overhead makes it faster than divide-and-conquer algorithms for tiny inputs. Many optimized implementations of quicksort and merge sort switch to insertion sort below a threshold.
  • Nearly sorted data: If most elements are already close to their final position, insertion sort runs in nearly O(n) time.
  • Online sorting: When data arrives one element at a time (streaming), insertion sort naturally handles each new element as it comes.
  • Stable sort required: Insertion sort preserves the relative order of equal elements, making it stable.

When to Avoid It

For large datasets (n > 1000), insertion sort's O(n²) performance is unacceptable. Use merge sort, quicksort, or heapsort instead. At n = 10,000, insertion sort performs roughly 50 million comparisons while merge sort does about 130,000.

Key Properties

PropertyValue
In-placeYes
StableYes
AdaptiveYes (faster on nearly sorted input)
OnlineYes (can sort as data arrives)