Insertion Sort Explained: Worked Example, Complexity and Exam Traps

Learn how insertion sort grows a sorted prefix, trace every pass on a five-element array, and avoid mistakes when counting comparisons, shifts, and writes.

KnowledgeGate Team

Exam prep & CS education

Updated 4 Dec 20265 min read
Insertion Sort Explained: Worked Example, Complexity and Exam Traps

Insertion sort often looks like repeated swapping, which makes comparison and movement counts surprisingly easy to get wrong. Its real operation is simpler: save one key and insert it into an already sorted prefix by shifting larger elements to the right. This process determines its comparison and shift counts, complexity, stability, and common exam traps.

Insertion Sort Mechanics: Save, Shift, Insert

Think of arranging playing cards. The cards on the left form a sorted group. Take the next card, move each larger card one place right, and insert the new card into the gap.

For an array, A[0] is a sorted one-element prefix. Before pass i, the loop invariant says that A[0..i-1] is sorted and contains the original prefix elements. Inserting A[i] establishes the claim for A[0..i]. This gives initialisation, maintenance, and termination when the prefix covers the whole array.

An evaluation of A[j] > key is a key comparison, and A[j + 1] = A[j] is a shift. The final A[j + 1] = key is a placement write, not a shift.

Insertion Sort Algorithm, Index Movement and the Sorted-Prefix Invariant

Here is language-neutral pseudocode with zero-based indices:

Code
for i = 1 to n - 1
    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

Saving key before shifting prevents a prefix element from overwriting the value being inserted.

On the final pass, the array is [2, 4, 6, 8, 7], with [2, 4, 6, 8] as its sorted prefix. At i = 4, save key = 7; 8 > 7 shifts 8 from A[3] to A[4]. Then 6 > 7 is false, so write 7 to A[3], producing [2, 4, 6, 7, 8].

Horizontal insertion-sort array for pass i = 4 shows [2, 4, 6, 8, 7] becoming [2, 4, 6, 7, 8] after key 7 shifts 8 once.

Insertion Sort Worked Example: Sort [8, 4, 6, 2, 7]

Start with [8, 4, 6, 2, 7]. Each pass takes the first element outside the sorted prefix and inserts it:

  • At i = 1, key 4 makes 8 shift right: [4, 8, 6, 2, 7]. Count 1 comparison and 1 shift.

  • At i = 2, key 6 makes 8 shift, then 4 > 6 is false: [4, 6, 8, 2, 7]. Count 2 comparisons and 1 shift.

  • At i = 3, key 2 is smaller than 8, 6, and 4, so all three shift: [2, 4, 6, 8, 7]. Count 3 comparisons and 3 shifts. After 4 > 2, j becomes -1; the bounds check stops the loop without another key comparison.

  • At i = 4, key 7 makes 8 shift, then 6 > 7 is false: [2, 4, 6, 7, 8]. Count 2 comparisons and 1 shift.

Pass

Key

Key comparisons in order

Shifts

Array after insertion

Start

Not applicable

Not applicable

0

[8, 4, 6, 2, 7]

i = 1

4

8 > 4

1

[4, 8, 6, 2, 7]

i = 2

6

8 > 6, then 4 > 6 is false

1

[4, 6, 8, 2, 7]

i = 3

2

8 > 2, then 6 > 2, then 4 > 2

3

[2, 4, 6, 8, 7]

i = 4

7

8 > 7, then 6 > 7 is false

1

[2, 4, 6, 7, 8]

The totals are 1 + 2 + 3 + 2 = 8 key comparisons and 1 + 1 + 3 + 1 = 6 shifts. Four final key-placement writes, one per pass, make 6 + 4 = 10 array writes under this convention. Do not call them 10 shifts.

Insertion-sort trace table for A = [8, 4, 6, 2, 7] shows four passes and the final sorted array, with 8 comparisons, 6 shifts, and 4 placement writes.

Insertion Sort Time and Space Complexity, With Exact Boundary Cases

On sorted input [1, 2, 3, 4, 5], each of four passes performs one failed key comparison and no shift. The exact totals are 4 comparisons and 0 shifts, so the running time is Theta(n). Insertion sort is adaptive because nearly sorted input also needs relatively few shifts.

On reverse input [5, 4, 3, 2, 1], pass i compares with and shifts all i prefix elements. For five elements, each total is 1 + 2 + 3 + 4 = 10. In general,

1 + 2 + ... + (n - 1) = n(n - 1)/2.

That gives Theta(n^2) comparisons and shifts in the worst case. Average-case time is also Theta(n^2). These are tight bounds, a distinction explained further in Time Complexity and Asymptotic Notation.

The iterative algorithm uses Theta(1) auxiliary space: one saved key plus index variables, while the input array itself is rearranged. There is no recursion stack to count.

Insertion Sort Stability, In-Place Behaviour and When It Fits

Sort labelled records [(4,A), (2,X), (4,B), (3,Y)] by numeric key. Under the strict condition A[j] > key, equal records never cross, so the result is [(2,X), (3,Y), (4,A), (4,B)]. Their A-before-B order is preserved. With A[j] >= key, an equal element may move past the new key and destroy stability.

Standard insertion sort is stable, in-place, and online: each arriving element can enter the processed prefix. It suits small or nearly sorted inputs, but quadratic growth makes it poor for large, disorderly arrays. Sorting Algorithms: Complete Guide with Worked Examples for GATE CS and Interviews compares the wider family through insertion and quicksort traces; use the index, shift, and placement-write convention above when a question isolates insertion sort.

Insertion Sort Exam Questions and Traps

An exam question can ask for the array after a named pass, counts under a stated convention, best or worst complexity, stability, or the effect of changing > to >=. A useful checkpoint: after passes i = 1, 2, 3, the state is [2, 4, 6, 8, 7], not the final array.

Keep these corrections beside your rough work:

  • The processed prefix is sorted, but its elements are not necessarily in their final global positions during an early pass.

  • A shift is one assignment to the next array cell. It is not automatically a swap.

  • A failed comparison counts when A[j] is actually compared with key. If j becomes -1, stopping on the bounds check adds no key comparison.

  • Best-case time is Theta(n), not Theta(n^2).

  • Stability depends on equal keys not being moved past one another.

The GATE CS Exam Preparation Courses & Test Series page connects insertion sort to wider Algorithms coverage. Trace practice questions by hand and label each miss as an indexing, counting-convention, or property error. For timed subject-wise mocks, continue with the GATE Test Series.

Insertion Sort: The Short Version and Next Step

Insertion sort grows a sorted prefix. Each pass saves one key, shifts larger prefix elements right, and inserts the key into the gap. Under the standard strict comparison, the algorithm is stable and in-place. Its time ranges from Theta(n) on sorted input to Theta(n^2) on average and in the worst case.

Retrace [8, 4, 6, 2, 7] without looking and confirm 8 comparisons and 6 shifts. Then derive 10 of each for the reverse five-element array. For a structured, subject-by-subject route, use GATE Guidance by Sanchit Sir.