CLRS Chapter: 2.1

Worst-case Complexity: O(n²)

Space Complexity: O(1)

Technical Sheet. Based on Introduction to Algorithms (Cormen et al., 4th Edition), Chapter 2 (Section 2.1: Insertion sort).


1. The Sorting Problem and the Insertion Sort Approach

The basic sorting problem consists of taking a sequence of nn numbers and rearranging them into a monotonically increasing order.

Input: a sequence of nn numbers ⟨a1,a2,…,an⟩\langle a_1, a_2, \dots, a_n \rangle.

Output: a permutation ⟨a1′,a2′,…,an′⟩\langle a'_1, a'_2, \dots, a'_n \rangle of the input sequence such that:

a1′≤a2′≤⋯≤an′a'_1 \le a'_2 \le \dots \le a'_n

The elements to be sorted are known as keys. In computational practice, keys are often associated with additional data called satellite data. Together, the key and its satellite data form a record (for instance, a student’s data in a database ordered by their GPA).

How Does Insertion Sort Work?

Insertion Sort is an efficient algorithm for sorting a small number of elements. Its operation is identical to the way a person sorts a hand of playing cards:

  1. Start with an empty left hand and the cards face down on the table.
  2. Draw one card at a time from the table and insert it into its correct position within the left hand.
  3. To find the correct position, compare the new card with the ones already in the hand, from right to left.
  4. At all times, the cards in the left hand are kept sorted.

2. Pseudocode Specification

The INSERTION-SORT procedure takes an array AA and the number of elements nn, operating over the index range A[1…n]A[1 \dots n].

INSERTION-SORT(A, n)
1  for i = 2 to n
2      key = A[i]
3      // Insert A[i] into the sorted subarray A[1 .. i - 1]
4      j = i - 1
5      while j > 0 and A[j] > key
6          A[j + 1] = A[j]
7          j = j - 1
8      A[j + 1] = key

3. Proof of Correctness Using Loop Invariants

To prove that an algorithm is correct, the technique of loop invariants is used, which is a form of mathematical induction. An invariant must satisfy three properties:

  1. Initialization. It is true prior to the first iteration of the loop (base case).
  2. Maintenance. If it is true before an iteration, it remains true before the next one (inductive step).
  3. Termination. When the loop terminates, the invariant gives a useful property that helps show that the algorithm is correct.

Applying the Invariant to Insertion Sort

Invariant. At the start of each iteration of the for loop (lines 1–8), the subarray consisting of elements A[1…i−1]A[1 \dots i-1] consists of the elements originally present in A[1…i−1]A[1 \dots i-1], but now in ascending order.

Proof.

  • Initialization. When i=2i = 2, the subarray A[1…i−1]A[1 \dots i-1] contains only A[1]A[1], which is the original element. By definition, a subarray of a single element is sorted. The invariant holds.
  • Maintenance. The loop body moves elements A[i−1],A[i−2],…A[i-1], A[i-2], \dots one position to the right until finding the right spot for the key (lines 4–7) and inserts it into the correct position (line 8). This extends the sorted subarray to A[1…i]A[1 \dots i]. Incrementing ii for the next iteration preserves the invariant.
  • Termination. The loop terminates when ii exceeds nn (that is, when i=n+1i = n + 1). Substituting ii by n+1n + 1 in the invariant statement, the subarray A[1…n]A[1 \dots n] contains all the original elements completely sorted. Therefore, the algorithm is correct.

4. C++20 Implementation

Translation of the pseudocode into C++20, adapted to the language’s zero-based indexing while preserving CLRS logic:

#include <iostream>
#include <vector>

// Insertion Sort implementation based on CLRS (Cormen)
template <typename T>
void insertionSort(std::vector<T>& A) {
    const size_t n = A.size();

    // Iterate from the second element (index 1) to the end
    for (size_t i = 1; i < n; ++i) {
        T key = A[i];
        int j = static_cast<int>(i) - 1;

        // Shift elements greater than the key to the right
        while (j >= 0 && A[j] > key) {
            A[j + 1] = A[j];
            j--;
        }

        // Insert the key into its correct position
        A[j + 1] = key;
    }
}

int main() {
    std::vector<int> A = {5, 2, 4, 6, 1, 3};

    std::cout << "Original array: ";
    for (int x : A) std::cout << x << " ";
    std::cout << "\n";

    insertionSort(A);

    std::cout << "Sorted array:   ";
    for (int x : A) std::cout << x << " ";
    std::cout << "\n";

    return 0;
}

5. Running Time Analysis

The running time of Insertion Sort depends on the input instance. The algorithm sorts in place: it only uses a constant amount of additional memory, O(1)O(1).

Best Case

If the array is already completely sorted, the while condition (A[j]>keyA[j] > \textit{key}) is never met. The running time is linear in the size of the input:

T(n)=O(n)T(n) = O(n)

Worst Case

If the array is sorted in strictly descending order, the algorithm compares each new element with all previous elements in the sorted subarray. The number of operations is quadratic:

T(n)=O(n2)T(n) = O(n^2)