Previous Topic
parent_topic
0.88
Provides the foundational concepts and criteria that insertion sort exemplifies and makes tangible through implementation and analysis.
foundational_overview
0.84
Frames the motivations and key properties that insertion sort exemplifies, preparing learners to implement and analyze it.
sorting_algorithm
0.82
Serves as a baseline simple comparison-based sort whose mechanics and complexity are contrasted with insertion sort.
sorting_algorithm
0.78
Provides a baseline for comparing swap counts, stability, and adaptiveness when learning insertion sort.

Insertion Sort

algorithms data structures software engineering
Insertion sort is a simple, comparison-based sorting algorithm that builds a sorted portion of the list one element at a time by inserting each new element into its correct position. It is in-place, stable, and adaptive, making it efficient for small or nearly sorted datasets, but it has quadratic time complexity in the average and worst cases.

What Is Insertion Sort?

Insertion sort is a straightforward sorting algorithm that processes a collection (often an array or list) from left to right, maintaining a growing sorted prefix. For each element, it finds the correct position within the already-sorted portion and inserts it there, shifting larger elements to the right as needed.

How It Works

  1. Assume the first element is trivially sorted.
  2. Pick the next element (the "key").
  3. Scan left through the sorted portion, shifting elements that are greater than the key one position to the right.
  4. Insert the key into the first position where it is not less than the element to its left.
  5. Repeat until all elements are processed.

Example

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

  • Start with [5] | [2, 4, 6, 1, 3]
  • Insert 2: [2, 5] | [4, 6, 1, 3]
  • Insert 4: [2, 4, 5] | [6, 1, 3]
  • Insert 6: [2, 4, 5, 6] | [1, 3]
  • Insert 1: [1, 2, 4, 5, 6] | [3]
  • Insert 3: [1, 2, 3, 4, 5, 6]

Pseudocode

for i from 1 to n-1:        # 0-based indexing
    key = A[i]
    j = i - 1
    while j >= 0 and A[j] > key:
        A[j + 1] = A[j]
        j = j - 1
    A[j + 1] = key

Properties and Complexity

  • In-place: Yes (O(1) extra space)
  • Stable: Yes (equal elements keep their relative order)
  • Adaptive: Yes (runs fast on nearly sorted data)
  • Online: Yes (can sort as elements arrive)
  • Time complexity:
    • Best case (already sorted): O(n)
    • Average case: O(n^2)
    • Worst case (reverse sorted): O(n^2)
  • Space complexity: O(1) auxiliary space

When to Use It

  • Small arrays or lists (often used as a base case in hybrid sorts)
  • Nearly sorted data where few shifts are needed
  • Streaming or interactive scenarios (online sorting)
  • When stability matters and dataset size is modest

Variants and Related Ideas

  • Binary insertion sort: Uses binary search to find the insertion point (still O(n^2) due to shifts).
  • Shell sort: Generalizes insertion sort by comparing elements far apart, improving performance.
  • Hybrid algorithms: Many library sorts switch to insertion sort for small subarrays.

Implementations

Python

def insertion_sort(a):
    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
    return a

JavaScript

function insertionSort(arr) {
  for (let i = 1; i < arr.length; i++) {
    const key = arr[i];
    let j = i - 1;
    while (j >= 0 && arr[j] > key) {
      arr[j + 1] = arr[j];
      j--;
    }
    arr[j + 1] = key;
  }
  return arr;
}

Common Pitfalls

  • Forgetting to handle the left boundary (j can go to -1).
  • Not preserving stability by using the wrong comparison when equal (use > rather than >= when shifting).
  • Expecting good performance on large, random datasets (it will be O(n^2)).

Practice Ideas

  • Modify the implementation to count shifts and comparisons.
  • Implement binary insertion sort and compare run times.
  • Use insertion sort as a base case within merge sort or quicksort for small subarrays.

Context from Referenced By

Context from Related Topics
Pop Quiz
Topic: insertion_sort
Level: 1
True or False:

Using binary search to find the insertion point in insertion sort reduces its overall time complexity to O(n log n).

Topic: insertion_sort
Level: 1
Multiple Choice:

Which property of insertion sort ensures that equal elements retain their original relative order after sorting?

Topic: insertion_sort
Level: 1
Fill in the Blank:

In its best-case scenario (already sorted input), insertion sort runs in _____ time.

Topic: insertion_sort
Level: 2
True or False:

Insertion sort is an online algorithm that can sort as elements arrive.

Topic: insertion_sort
Level: 2
Multiple Choice:

In a standard insertion sort, which inner-loop condition preserves stability when shifting elements before inserting the key?

Topic: insertion_sort
Level: 2
Fill in the Blank:

Insertion sort is in-place and requires _____ auxiliary space.

Topic: insertion_sort
Level: 3
True or False:

Reverse-sorted input triggers the worst-case runtime for insertion sort.

Topic: insertion_sort
Level: 3
Multiple Choice:

In the provided insertion sort pseudocode, what loop invariant holds at the start of each outer iteration i?

Topic: insertion_sort
Level: 3
Fill in the Blank:

Insertion sort maintains a growing sorted _____ at the beginning of the array.

Topic: insertion_sort
Level: 4
True or False:

The total number of element shifts performed by the inner loop of insertion sort equals the number of inversions in the input array.

Topic: insertion_sort
Level: 4
Multiple Choice:

In the provided insertion sort pseudocode, why is the key inserted at A[j + 1] after the inner while loop terminates?

Topic: insertion_sort
Level: 4
Fill in the Blank:

Binary insertion sort uses binary search to find the insertion point, but its overall time remains O(n^2) due to the O(n) cost of _____ per insertion.

Topic: insertion_sort
Level: 5
True or False:

Insertion sort is adaptive, running faster on nearly sorted data because fewer shifts are needed.

Topic: insertion_sort
Level: 5
Multiple Choice:

Which algorithm is a variant that generalizes insertion sort by comparing elements far apart to improve performance?

Topic: insertion_sort
Level: 5
Fill in the Blank:

In insertion sort, during the inner loop, elements greater than the key are shifted one position to the _____.

Next Topic
used_by
0.88

Shell Sort
Shell sort performs gapped insertion sorts as its core step, effectively using insertion sort on sublists defined by decreasing gap sequences.
used_by
0.86

Timsort
Timsort uses insertion sort on small runs to efficiently finalize locally sorted segments before merging.
used_by
0.86

Shell Sort
Shell sort generalizes insertion sort by applying insertion-like passes over elements separated by decreasing gaps, ending with a final pass at gap 1 that is exactly insertion sort.
used_by
0.82

Binary Insertion Sort
Binary insertion sort leverages insertion sort’s in-place insertion and shifting, but finds the insertion position with binary search to reduce comparisons.
used_by
0.82

Shell Sort
Shell sort generalizes insertion sort by applying insertion-like passes on gapped subsequences; understanding insertion sort clarifies Shell sort’s inner mechanism.
used_by
0.78

Bucket Sort
Bucket sort commonly uses insertion sort to sort elements within each bucket because insertion sort is efficient on small, nearly sorted subsets.
related_to
0.75

Merge Sort
Merge Sort is another sorting algorithm, typically more efficient for large data sets compared to Insertion Sort.
related_to
0.75

Quick Sort
Quick Sort is another sorting algorithm that can handle larger datasets more efficiently than Insertion Sort.