TactivergeLite

Lite / Intelligent Robotic Systems / Week 5

Insertion sort: tidy as you go

Parts come off a line nearly in order of mass, with the odd one out of place. Which simple sort hardly has to do any work at all?

About 40 min · 3 goals · Checked by automated tests · Full interactive version

Why should I care?

Sorting is everywhere: ranking test runs, ordering waypoints, preparing data for binary search. Insertion sort is how most people sort a hand of cards, and it has a superpower: on data that's already nearly sorted it is extremely fast.

Predict

Insertion sort and selection sort race on an already sorted list of 10 items. Which makes fewer comparisons?

  1. Insertion sort
  2. Selection sort
  3. They tie
Guess first, then reveal

Insertion sort: 9 comparisons (each new item checks its left neighbour once and stays). Selection sort always makes 10·9/2 = 45, because it scans the whole remaining list for the minimum whatever the input.

Discover

Race the two sorts on each input order. Record the total comparisons for n = 8 in a table: shuffled, nearly sorted, sorted, reversed. When does insertion sort tie with selection sort? Check the n − 1 and n(n − 1)/2 rules.

What the interactive shows (text version)

The sorting race shows two bar charts of the same input, one for insertion sort and one for selection sort, with a running comparison count. For n = 8: sorted input costs insertion sort 7 comparisons and selection sort 28; reversed input costs both 28; shuffled input usually costs insertion sort noticeably fewer.

You can also open the interactive on the full site when you have a faster connection.

Watch (optional)

Watch for: Watch how the presenter counts the work each sort does and why the count matters more than the code length.

Compares simple sorts by counting the work they do, and introduces big-O as a way to talk about how that work grows.

“Getting Sorted & Big O Notation - Computerphile” by Computerphile (opens YouTube; streaming video uses a lot of data)

The video is optional. Everything you need is in this lesson's text.

Understand

Grow a sorted part on the left

Treat a[0] as sorted. Take the next item (the key) and shift bigger items in the sorted part one place right until you meet one that isn't bigger, then drop the key in the gap. Repeat for every item. The sorted part grows by one each pass.

Counting comparisons

Each comparison is one test of a[j] > key. A key passes over every bigger item to its left, plus one more comparison where it stops (unless it reaches the front). Sorted input: 1 comparison per key, n − 1 in total. Reversed: every key travels to the front, 1 + 2 + … + (n − 1) = n(n − 1)/2.

Stable and in place

Insertion sort never moves equal items past each other (it is stable), and it needs no extra list (it is in place). It is quadratic in the worst case, so for big shuffled data you'd use Python's built-in sorted(), which is O(n log n).

Explain it another way

Intuitive

Sort a hand of cards by picking up one at a time and sliding it left into place among the cards you already hold.

Technical

Best case O(n), worst and average case O(n²) comparisons and moves. The number of shifts equals the number of inversions (pairs that are out of order), so it is fast whenever inversions are few.

Mathematical

If the input has I inversions, insertion sort makes I shifts and between I and I + n − 1 comparisons. A reversed list of n has n(n − 1)/2 inversions, the maximum.

Applied

Fast general-purpose sorts, including Python's own (Timsort), switch to insertion sort on short runs of data because it is so quick on small or nearly sorted pieces.

Worked example 1

Insertion sort that counts comparisons, on part masses in grams.

def insertion_sort(a):
    """Sort list a in place. Returns the number of a[j] > key comparisons."""
    comparisons = 0
    for i in range(1, len(a)):
        key = a[i]
        j = i - 1
        while j >= 0:
            comparisons += 1
            if a[j] > key:
                a[j + 1] = a[j]
                j -= 1
            else:
                break
        a[j + 1] = key
    return comparisons


masses = [5, 2, 4, 6, 1, 3]
print(insertion_sort(masses), masses)      # 12 [1, 2, 3, 4, 5, 6]
print(insertion_sort([1, 2, 3, 4, 5, 6]))  # 5  (n - 1)
print(insertion_sort([6, 5, 4, 3, 2, 1]))  # 15 (n(n-1)/2)

Common mix-ups

Practice

Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.

comparisons

comparisons

comparisons

Practice 4. A 1,000-item log is sorted except for two neighbouring entries that are swapped. Roughly how many comparisons does insertion sort make?
Practice 5. Two runs both drew 1.5 A; run 4 is listed before run 9. After a stable sort by current, which comes first?

Apply it

Generate lists of 100, 200 and 400 random numbers, and nearly sorted lists of the same sizes. Count insertion-sort comparisons for each and put them in a table. Does doubling n roughly quadruple the count for random data? What happens for nearly sorted data?

Reflect

Where in your work does data arrive nearly sorted already? What does that mean for the sort you should choose?

Write your answer on paper or in your own notes. Lite never stores what you write.

Go further

← Halve it again: binary searchSort once, search many: when sorting pays →