1nums = [6,3,5,8,1,5,7,2]2out = sorted(nums)01234567635a815b72
Bars: one number each; height = valueMemory row: eight numbered slots, nums[0] to nums[7]Spare row: where merge sort builds a merged runCode card: the Python that sorts the listEach bar is one number in a slot of memory; its height is its value. Insertion sort lifts the next bar, slides the bigger bars in the sorted part one slot right and drops the bar into the gap. Merge sort stands walls between the slots until every piece holds one bar, then merges neighbouring runs by copying the smaller front bar into the spare row, and copies each merged run back. The marks a and b are only labels in the drawing so you can tell the two 5s apart; Python sees two equal 5s.

Why sort

  1. Line 1 puts eight numbers in a row of memory, one per numbered slot. Sorting puts them in order, smallest first. Sorted data is easier to use: binary search works, and the smallest and largest sit at the two ends.

Insertion sort

Merge sort

Stability and Python

The Python behind the step

;; step 1/10 · Why sort?
>>> nums = [6, 3, 5, 8, 1, 5, 7, 2]
>>> nums[0], nums[7]       # unsorted: the ends tell you nothing
(6, 2)
>>> s = sorted(nums)
>>> s[0], s[-1]            # sorted: smallest and largest
(1, 8)

O(n²) and O(n log n) describe how the work grows as the number of items n grows, ignoring constant factors. log₂ n is how many times n can be halved before reaching 1 (log₂ 8 = 3). CPython's sort uses binary insertion sort to build short runs, so for fewer than 64 items it is binary insertion sort alone. Since Python 3.11 it decides the order of merges with Munro and Wild's powersort policy.