Module 2 of 39

Insertion sort: a worked example and its cost

Trace insertion sort, explain why it works, and compare its work with a divide-and-conquer approach.

Suppose a small group of people writes their arrival times on slips of paper. You want the slips in order, earliest first. One natural method is to keep a sorted pile and place each new slip where it belongs. Insertion sort does that inside a list. It is a useful first algorithm because we can follow every step and explain why the result is sorted.

Background for this page. You should be able to follow a loop and read a list by position. Python positions start at zero. Ascending order means every value is no greater than the next. Related explanations: Algorithms: inputs, outputs, and correctness · Big O, Big Omega, and Big Theta.

2.1 Build a sorted portion

Start with [7, 3, 5, 2]. Treat the first value, 7, as a sorted portion of length one. Take 3. Move 7 one place right and put 3 before it: [3, 7, 5, 2]. Take 5 and put it between 3 and 7: [3, 5, 7, 2]. Finally, move 7, 5, and 3 right to make room for 2: [2, 3, 5, 7].

Value to insertSorted portion afterward
Start[7]
3[3, 7]
5[3, 5, 7]
2[2, 3, 5, 7]

Insertion sort holds 2 aside, shifts 7, then 5, then 3 to the right, and places 2 in the empty first position

The dashed box is the empty position. The green boxes show the value just moved. After three shifts, there is room to place 2 at the front.

You can also move through the full example one insertion at a time:

Step through insertion sort

Step 1 of 4. Start with 7 as the sorted portion. Order: 7, 3, 5, 2.

  1. 7
  2. 3
  3. 5
  4. 2

The important idea is an invariant: before each new value is inserted, the portion to its left is sorted. Inserting the new value in the right place preserves that property. When there are no values left, the sorted portion is the whole list. That is a short explanation of correctness, not just a report that our example happened to work.

2.2 Turn the idea into code

This Python function makes a copy so it leaves the caller’s list alone. It assumes the items can be compared with < and should be in ascending order.

# Return a sorted copy of the values.
def insertion_sort(values):
    # Copy the input so it stays unchanged.
    result = list(values)
    # One item is already sorted. Start at the second.
    for position in range(1, len(result)):
        # Hold the item while making a space for it.
        item = result[position]
        # Begin with the item just to its left.
        left = position - 1
        # Keep moving larger items right.
        while left >= 0 and result[left] > item:
            # Shift the larger item one place.
            result[left + 1] = result[left]
            # Look one place further left.
            left -= 1
        # Put the held item into the space.
        result[left + 1] = item
    # Give back the new, sorted list.
    return result

For example, insertion_sort([7, 3, 5, 2]) returns [2, 3, 5, 7]. If the list is empty or has one item, the outer loop does nothing and the copy is returned. If two equal values appear, this version does not move the earlier equal value past the later one. That property is called stability; it can matter when records have other fields besides the sorting key.

2.3 Count what the algorithm does

If the input is already sorted, the inner loop checks each new item and performs no shifts. The work grows roughly with the number of items. If the list is in reverse order, each new item must pass all earlier items. For n items, the number of shifts is 1 + 2 + ... + (n - 1), which grows roughly like n². We will put precise names on these growth rates in the next module.

That does not make insertion sort useless. For a small list, its simplicity can be valuable. It also handles a list that is already nearly sorted with relatively little shifting. A choice of algorithm depends on the size and shape of the input, not only on one number from a table.

Now imagine splitting the list into halves, sorting each half, and merging the two sorted halves. That is the central idea of merge sort, a divide-and-conquer method. It generally does more setup, but its work grows more gently on large inputs. We will examine divide and conquer in module 4. For now, the useful comparison is conceptual: insertion sort extends one sorted portion; merge sort sorts separate portions and combines them.

2.4 Define what sorted means

Sorting requires a rule. If the values are numbers, ascending order is clear enough. If they are names, should uppercase and lowercase matter? If they are records with equal arrival times, should their original order remain? If an entry has no arrival time, where should it go? The algorithm cannot settle these questions for you. They belong in the problem definition.

Why shifting does not lose a value

For [3, 7, 5], save 5 outside the array, then shift 7 right. The temporary array looks like [3, 7, 7], but one position is a gap waiting for the saved key. Put 5 there to obtain [3, 5, 7]. Every shifted value exceeds the key, while the value before the gap does not. That is why insertion preserves the sorted prefix. The implementation works on a copy and returns that sorted copy, so the caller retains the original list.

Practice. Trace insertion sort on [4, 1, 3, 1]. Show the list after each insertion. How many shifts happen? What happens to the order of the two equal 1 values?

Answer. The states are [1, 4, 3, 1], [1, 3, 4, 1], and [1, 1, 3, 4]. There are 1, 1, and 2 shifts, for 4 total. Because the comparison is >, not >=, the first 1 stays before the second 1. You could attach labels to equal values to see that order clearly.

In the next module we will compare algorithms without tying the answer to one computer or one stopwatch reading.

Try another case. Which four distinct values cause six shifts?

Reasoning. A reverse-sorted input such as [4, 3, 2, 1] causes 1, then 2, then 3 shifts. Each new key crosses the entire sorted prefix.

View the full course and choose another topic.

Image preview

Fit