Insertion Sort: Building Order One Value at a Time

When you arrange playing cards in your hand, you can take each new card and slide it into the cards already arranged. Insertion sort follows this pattern: it builds an ordered beginning of an array by inserting one value at a time. It is useful for small inputs and inputs that already have substantial order. Here, you will sort into ascending order, allowing equal values to remain beside one another.

Grow a sorted prefix

A sorted prefix is a consecutive group of entries beginning at index zero whose values are already in order. Initially, the first entry forms a sorted prefix by itself. The first pass processes index 1, the second processes index 2, and so on.


Before processing index ii, the governing condition is


a0≤a1≤⋯≤ai−1.a_0 \le a_1 \le \cdots \le a_{i-1}.


The pass inserts the value at index ii into this prefix. Afterwards, entries from index zero through index ii are ordered. The remaining entries have not yet been processed; they need not be larger than the prefix values.


This is a loop invariant. It explains correctness: the prefix starts sorted, each insertion preserves its order while extending it, and the last pass extends it across the entire array.



Carry out one insertion

Save the next value as the key. Starting at the prefix's right edge, compare entries with the key. Shift each larger entry one position right. Stop at an entry no greater than the key, or when you pass the array's left edge. Write the saved key into the resulting position.


Example: With prefix 4, 9, 15 and next value 7, save 7, shift 15 and 9 right, and stop at 4. Insert 7 after 4. The prefix becomes 4, 7, 9, 15.


Three stages show inserting 7 into the sorted prefix 4, 9, 15.


This Python implementation uses zero-based indices:


Python
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


The final position is j + 1: either immediately after the entry that stopped the search, or index zero when j becomes negative. Save the key before shifting, because a shift may overwrite its original array position.



Work, order, and storage

A shift copies an existing entry rightward; writing the saved key into place is a separate operation. A key comparison evaluates a[j] > key. Index checks are separate from key comparisons.


For n≥2n \ge 2, input order changes the work substantially:


Input order

Key comparisons

Shifts

Running-time growth

Already ascending

n−1n-1

00

Linear, O(n)O(n)

Descending, distinct values

n(n−1)/2n(n-1)/2

n(n−1)/2n(n-1)/2

Quadratic, O(n2)O(n^2)


Here, Big O notation describes growth rather than an exact elapsed time. In the descending case, successive keys cross 1, 2, and eventually n−1n-1 earlier entries:


1+2+⋯+(n−1)=n(n−1)2.1+2+\cdots+(n-1)=\frac{n(n-1)}{2}.


Nearly ordered inputs can need few shifts, although one small value near the end can still move across a long prefix. Input order matters alongside input size.


Using strictly greater than the key as the shift condition gives stability: a later equal-valued record does not move ahead of an earlier one. The implementation also uses O(1)O(1) extra storage: a saved key and a few indices, rather than another array that grows with the input.

What to remember

  • Before each pass, the prefix is sorted.
  • Save the key, shift larger entries right, then insert the key.
  • The strict comparison preserves equal-value order.
  • Already ordered input takes linear time; the worst case takes quadratic time.

Example: Ordering Short Audio Clips

An editor sorts audio-clip durations [26, 14, 20, 11, 23], measured in seconds, using ascending insertion sort. Indices begin at zero, and each pass shifts only entries strictly greater than the saved key. A shift is a copy of an existing entry one position right; placing the saved key is counted separately.


a) What is the complete array after the first two passes?


The first pass processes index 1. The saved key is ________, and the preceding duration is ________. Since 26 is greater than 14, copy 26 from index zero to index 1. The index being checked becomes negative, so place 14 at index zero.


After the first pass, the array, in seconds, is [14, 26, 20, 11, 23].


The second pass saves 20 s from index 2. Compare 26 with 20 and shift 26 from index 1 to index 2. Then compare 14 with 20. Since 14 is not greater, stop and place 20 at index 1.


The answer after two passes is [14, 20, 26, 11, 23], with durations in seconds. Each of these passes used one shift.


b) What is the complete array after the third pass?


Save 11 s from index 3. The existing sorted prefix is 14, 20, 26, in seconds.


Compare 26 with 11 and copy 26 from index 2 to index 3. Compare 20 with 11 and copy 20 from index 1 to index 2. Compare 14 with 11 and copy 14 from index zero to index 1.


These copies make ________ shifts. The checking index is now negative, so place the saved 11 s at index zero. Keep the saved key separate while its original position is overwritten.


The answer after the third pass is [11, 14, 20, 26, 23], with durations in seconds. Only the first four entries are guaranteed to be ordered at this stage.


c) Complete the sort and find the total number of shifts across all four passes.


The final key is 23 s. The largest duration in the existing prefix is ________. Since 26 is greater than 23, shift it from index 3 to index 4. The next comparison is with 20 s, which is not greater than 23 s, so stop and place 23 s at index 3.


The final pass uses one shift. Before this pass, the first three passes had used ________ shifts in total: one for 14 s, one for 20 s, and three for 11 s.


Therefore,


Total shifts=1+1+3+1=6.\text{Total shifts}=1+1+3+1=6.


The final array is [11, 14, 20, 23, 26], with durations in seconds, and the total is 6 shifts. The four writes that place saved keys are excluded from this count.

An application sorts the priority values [16, 6, 13, 9] into ascending order using insertion sort. The first pass inserts the value at index 1; the second inserts the value at index 2. What is the complete array immediately after the second pass?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A programmer is documenting an insertion-sort implementation that arranges array values in ascending order. Match each term to its role during one pass.

Match each term
A.

Value saved temporarily while larger earlier values are copied right

B.

Index where the saved value is written after the backward scan stops

C.

Copying an earlier array value one position to the right

D.

Initial consecutive segment whose values are already in nondecreasing order

Key

Insertion position

Sorted prefix

Shift

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A scheduler sorts job durations [12, 18, 5, 15, 7], measured in milliseconds, using ascending insertion sort with zero-based indices. Shift entries only when they are strictly greater than the saved key.


A shift copies an existing entry one position right; writing the saved key into place does not count. For each pass, enter the number of shifts and the index where its saved key is placed. Give exact whole numbers in every input cell.

PassKey (ms)ShiftsKey final index
118
25
315
47

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice