Python 3D Academyবাংলা

Merge sort: merging two sorted piles

🌍 In real life. After the board exam, two invigilators each sorted their room's answer scripts by roll number. The office needs one pile in roll-number order. Nobody starts again from scratch: you put the two piles side by side, look at the top script of each pile, take the one with the smaller roll number, and repeat. Each look places one script, so 60 + 60 scripts need at most 119 looks.

But how did each room's pile get sorted? The same way: split the room's scripts between two helpers, let each sort their half, and merge the two halves. A helper with just one script has nothing to do. This is merge sort: the divide and conquer of Lesson 42.3, applied to sorting.

The idea in one sentence: merge sort splits the list in half, sorts each half the same way, and merges the two sorted halves by repeatedly taking the smaller of their front values.

Its words:

  • merge: join two sorted lists into one sorted list
  • front: the next value of a pile not yet taken; the fingers i and j point at the fronts
  • divide and conquer: split the problem, solve the parts, combine the answers (Lesson 42.3)
  • base case: a list of 0 or 1 values is already sorted

Merging, step by step:

  1. fingers i and j start at the front of each pile
  2. compare left[i] and right[j]; take the smaller one (the left one on a tie), and move that finger on
  3. when one pile is empty, add the whole rest of the other pile: it is already in order

Watch the two piles of roll numbers merge:

Merge sort, step by step:

  1. a list of 0 or 1 values is sorted: return it
  2. split it at mid = len(a) // 2
  3. merge sort the left half and the right half
  4. merge the two sorted halves

The list splits level by level until every part is a single value, then the parts merge back up (each merged part turns green):

Why it is correct. For the merge: the front of each pile is the smallest value left in that pile, so the smaller of the two fronts is the smallest value left in both piles. Taking it every time builds the output in order. When one pile runs out, the other's rest is in order and bigger than everything taken, so it goes on the end. For merge sort, use the three questions of Lesson 42.1: the smallest problem (0 or 1 values) is already sorted; trust the two recursive calls to sort their halves; and merging two sorted halves gives the whole list sorted.

What it costs, by counting. Merging n values takes at most n − 1 comparisons, one per value placed. Now read the tree level by level (Lesson 42.4): the list halves at every level, so there are about log₂ n levels, and the merges on each level handle all n values once, about n work per level. In all, about n log₂ n:

  • 8 values: at most 17 comparisons (the animation's list took 17)
  • 1,000 values: under 10,000, where insertion sort may need 499,500
  • 1,000,000 values: about 20 million, where the simple sorts need up to 500 billion

That is O(n log n) in the best, worst and average case alike: merge sort never has a bad input. The price is memory: merging builds new lists, O(n) extra. Because a tie takes from the left, merge sort is stable.

def merge(left, right):
    out = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:        # a tie takes from the left: stable
            out.append(left[i])
            i += 1
        else:
            out.append(right[j])
            j += 1
    out += left[i:]                    # one pile is empty: the rest
    out += right[j:]                   # of the other is already in order
    return out

def merge_sort(a):
    if len(a) <= 1:
        return a[:]                    # one paper is already sorted
    mid = len(a) // 2
    return merge(merge_sort(a[:mid]), merge_sort(a[mid:]))

print(merge([2, 5, 8], [1, 6, 9, 10]))
print(merge_sort([5, 2, 8, 1, 9, 3, 7, 4]))
rolls = [1042, 1007, 1031, 1019, 1007, 1050]
print(merge_sort(rolls), rolls)        # a new list; rolls is unchanged

Mistakes and edge cases.

  • forgetting the leftovers: without out += left[i:] and out += right[j:] the biggest values are lost
  • < instead of <= in merge: still sorted, but equal values from the right jump ahead of the left ones: no longer stable
  • a base case for 0 values only: a list of one value splits into [] and itself, forever: RecursionError: maximum recursion depth exceeded
  • mid = len(a) / 2: / gives a float, and slicing with a float is a TypeError; use //
  • empty piles: merge([], [3, 4]) must give [3, 4]; the leftovers line handles it

Quiz

  1. What does this print?

    def merge(left, right):
        out = []
        i = j = 0
        while i < len(left) and j < len(right):
            if left[i] <= right[j]:        # a tie takes from the left: stable
                out.append(left[i])
                i += 1
            else:
                out.append(right[j])
                j += 1
        out += left[i:]                    # one pile is empty: the rest
        out += right[j:]                   # of the other is already in order
        return out
    
    print(merge([1, 4, 9], [2, 3]))
    print(merge([], [5]), merge([7], []))
  2. When one pile runs out, why can the rest of the other pile go on the end without any comparing?

    • It is already in order, and every value in it is at least as big as everything taken
    • Because merge sort doesn't care about order at the end
    • Because the other pile was always the bigger one
  3. How much work does merge sort do on n values, and why?

    • About n log₂ n: about log₂ n levels of halving, and about n work to merge each level
    • About n²: every value is compared with every other
    • About log₂ n: it halves the list each time
  4. merge_sort([3, 1, 2]) never finishes: it ends in RecursionError. Which line is wrong?

    def merge_sort(a):
        if len(a) == 0:
            return a
        mid = len(a) // 2
        return merge(merge_sort(a[:mid]), merge_sort(a[mid:]))
  5. merge compares with left[i] <= right[j]. What changes if you write < instead?

    • Still sorted, but equal values from the right come first: merge sort stops being stable
    • The result is no longer sorted
    • Nothing at all

Coding tasks

  1. Write merge(left, right): both lists are sorted; return one new sorted list with all their values, by taking the smaller front each time (the left one on a tie). Don't use sort or sorted.

  2. Write merge_sort(a): return a new sorted list (leave a unchanged) by splitting in half, merge sorting each half and merging them. merge is given. On 300 values it must make fewer than 3,000 comparisons, where a simple sort makes about 22,000.