Skip to content
Tactiverge

School/○ Innovator/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

1.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.

  • ◇ Implement insertion sort and trace it by hand on a small array.
  • ◇ Count comparisons in the best case (n − 1) and worst case (n(n − 1)/2).
  • ◇ Compare insertion sort with selection sort on sorted, reversed and nearly sorted inputs.

2.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.

Loading the interactive…

Can't use the interactive? Read a description instead

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.

3.Checkpoint: guided practice

Check what you just discovered before going on. Hints appear after a wrong answer.

Practice 1 · a fresh version every time

Part masses (g) arrive as a = [32, 59, 17, 37, 44, 26]. They are sorted with insertion sort, where each new key moves left while j >= 0 and a[j] > key. Counting every evaluation of a[j] > key, how many comparisons are made?

comparisons

4.Predict

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

Guess first. Being wrong here is how the surprise works.

5.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

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

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

  • All simple sorts take the same time.
    ✓ Selection sort always makes n(n − 1)/2 comparisons; insertion sort adapts to how sorted the data already is.
  • You should write your own sort for real projects.
    ✓ Use sorted() or list.sort(). Write sorts to understand cost, then trust the tested library.

6.Watch

→ 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.

Length: see YouTube · captions on YouTube · source

Nothing loads from YouTube until you press play.

The video is optional: everything you need is also in the lesson text and the interactive.

7.Practice on your own

Practice, not a test. Wrong answers get a hint and another try.

Practice 2

How many comparisons does insertion sort make on a reversed list of 10 items?

comparisons

Practice 3 · a fresh version every time

Part masses (g) arrive as a = [36, 35, 27, 11, 5]. They are sorted with insertion sort, where each new key moves left while j >= 0 and a[j] > key. Counting every evaluation of a[j] > key, how many comparisons are made?

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?

8.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?

9.Reflect

10.Go further

Concepts: Algorithms, searching and complexity