← Course home

Search and ordering · Lesson 19 of 52

Merge sort

Derive merge sort's work from its levels and account for merge storage.

Full lessonAbout 10 min

You will learn to trace a stable merge and derive time and auxiliary-space costs.

Recommended first: Comparison sorts, Recursion and recurrences.

On this page 6 sections

The idea

merge_sort([3, 1, 4, 2]) returns [1, 2, 3, 4]. The first split is [3, 1] and [4, 2].

Merge sort splits the list in half, sorts each half, and merges the two sorted runs. The midpoint is len(values) // 2, integer division, so the halves differ by at most one item. The merge walks the two fronts and appends the smaller one. When the keys are equal it appends the left front, so equal keys keep the order they had in the input. The library merge_sort([3, 1, 4, 2]) returns [1, 2, 3, 4] and does not modify the input list.

A worked trace

StepStateWhat changed
Splitleft = [3, 1]Split into [3, 1] and [4, 2].
Splitleft = [3]Split into [3] and [1].
Takeoutput = [1]The merge takes 1. The output is [1].
Takeoutput = [1, 3]The merge takes 3. The output is [1, 3].
Splitleft = [4]Split into [4] and [2].
Takeoutput = [2]The merge takes 2. The output is [2].
Takeoutput = [2, 4]The merge takes 4. The output is [2, 4].
Takeoutput = [1]The merge takes 1. The output is [1].
Takeoutput = [1, 2]The merge takes 2. The output is [1, 2].
Takeoutput = [1, 2, 3]The merge takes 3. The output is [1, 2, 3].
Takeoutput = [1, 2, 3, 4]The merge takes 4. The output is [1, 2, 3, 4].

Why it is correct

A list of length 0 or 1 is already sorted, which is the base case. If both halves are sorted, the merge is sorted because every output item is the smaller remaining front. Nothing still in either run is smaller than that item. Stability follows from taking the left run on a tie. The left run holds the earlier original items of that key. The split keeps original order inside each half, and the recursive sorts are themselves stable.

A common mistake

Taking the right run on a tie moves an equal key in front of an earlier equal key.

What it costs

The recurrence is T(n) = 2 T(n/2) + Θ(n). There are Θ(log n) levels and Θ(n) work merging on each level, so the time is Θ(n log n) for every input order. Each level allocates new lists holding n items, so extra memory is Θ(n), plus Θ(log n) for the call stack. The sort is stable and it always pays the full n log n cost, including on sorted input.

Run it

python
from bitsandbytes.sorting.merge_sort import merge_sortprint(merge_sort([3, 1, 4, 2]))# prints: [1, 2, 3, 4] 

Practice and next step

Open Quicksort and partition next. Quicksort sorts in place and shows what an unlucky pivot costs.

Implementation and tests Optional reference

Library code 1

  • bitsandbytes.sorting.merge_sort

Use these references to compare the explanation with repository code and tests. A test link means it imports a lesson symbol; it does not by itself claim complete behavior coverage.

Step-by-step trace

Merge sort [3, 1, 4, 2]

Each half is sorted, then the two sorted runs are merged by taking the smaller front. Ties would take the left run, which is why the sort is stable. merge_sort returns [1, 2, 3, 4].

left
[3, 1]

State

  1. 03comparing
  2. 11comparing
  3. 24comparing
  4. 32comparing

Split into [3, 1] and [4, 2].

Practice with feedback

Check your understanding

Try each checkpoint before revealing the feedback. Ask for a hint when you need one. Answers and hints stay in this browser when local storage is available.

1Runs [2, 5] and [3, 4] have already written 2 and 3. Which value leaves next?
2A merge of n items does Θ(n) work, and there are Θ(log n) levels. What is the total?

Progress is never sent to an account or synced to another device. If local storage is blocked, choices last only until you leave this page.