Lesson 2 · Unit 03
Merge sort
Split, sort each half, merge: O(n log n) on every input
What you practise
- Split, recurse, merge
- Log n levels of n work
- O(n) extra space
- Stable
Try a question from this lesson
Pick one
You can merge two sorted lists quickly, but all you have is 8 unsorted numbers. How could merging alone sort them?
Correct answer
Treat each number as a sorted list of 1, then merge in pairs
Why
A single item is always sorted. Merge 8 singles into 4 sorted pairs, those into 2 sorted fours, those into 1 sorted eight. Merging the two halves directly fails: the halves are not sorted yet.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Merge sort
Merge sort sorts by merging. Split the list in half, sort each half by calling the same function, and merge the two sorted halves.
The base case is a list of 0 or 1 items, which is already sorted. Here merge is the two-pointer merge of two sorted lists.
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
return merge(left, right)function mergeSort(a) {
const n = a.length;
if (n <= 1) return a;
const mid = Math.floor(n / 2);
const left = mergeSort(a.slice(0, mid));
const right = mergeSort(a.slice(mid));
return merge(left, right);
}function mergeSort(
a: number[],
): number[] {
const n = a.length;
if (n <= 1) return a;
const mid = Math.floor(n / 2);
const left = mergeSort(a.slice(0, mid));
const right = mergeSort(a.slice(mid));
return merge(left, right);
}Python notea[:mid] and a[mid:] are slices: new lists holding the first mid items and the rest.
JavaScript notea.slice(0, mid) copies the items before index mid; a.slice(mid) copies from mid to the end.
TypeScript note): number[] { gives the return type. A function that calls itself needs it written out: TypeScript cannot infer it from its own result.
Concept
n log n, and its price
About log₂ n rounds, each handling all n items: merge sort is O(n log n). Shuffled, sorted or reversed input makes no difference.
It is also stable, because merge takes from the left half on ties.
The price is memory. Merging cannot be done inside the original list, so merge sort needs O(n) extra space for the merged copies. The simple sorts needed none.
9 more exercises in the app
- 2× type the answer
- 4× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.