Skip to the workspace
Pebellslearn by building
Recursion, Searching & Sorting  ›  Lesson

Merge Sort & Library Merge

Merge Sort 25 minSplit the list, sort each half recursively, and merge the sorted halves

dsa / Merge Sort & Library Merge

Explore each scene at your own pace.

01 · Merge a phone library with a laptop library

Merge a phone library with a laptop library

Merge Sort & Library Merge

Definition
Merge sort sorts a list by splitting it in half, sorting each half recursively, and merging the two sorted halves in one pass, which takes O(n log n) time however the input starts out.
In plain words
Cut a pile of cards in half until each pile is a single card, then zip piles back together two at a time, always taking the smaller top card. Zipping two already sorted piles is quick, and you do it level by level.

In short: merge sort is divide-and-conquer: split the list in half, sort each half by calling itself (recursion), then merge the two sorted halves with one pass of two pointers. The base case is 0 or 1 items. Every level of the split tree touches all n items once, and halving reaches size 1 after log₂ n levels, so the whole sort is O(n log n) — reliably, no matter how the input starts out — at the cost of O(n) extra space for the merges.

Two stacks of index cards, "phone" and "laptop", each already A→Z, with two fingers pointing at the top card of each and a single arrow sweeping them into one merged stack below

Merge a phone library with a laptop library

A listener signs in on a new laptop. Their phone library is sorted A→Z, and so is the laptop's. Gluing them together and re-sorting from scratch would throw away order you already have — merging walks the two fronts once and is done:

python
step through it
1a, b = [1, 4], [2, 3]
2out = []
3i = j = 0
4while i < len(a) and j < len(b):
5 if a[i] <= b[j]:
6 out.append(a[i])
7 i += 1
8 else:
9 out.append(b[j])
10 j += 1
11out.extend(a[i:])
12out.extend(b[j:])
13print(out)

The same merge, now on five play counts with every comparison drawn:

watch it move · array

The merge only ever compares the two fronts, so it finishes in one pass over both lists.

The fronts are 2 from a and 1 from b. 10 cells. i at index 0. j at index 2. k at index 5. Comparing 2 and 1.

1 / 7

The mistake: stopping as soon as either list runs out and forgetting the leftover copy. The tail of the longer list silently disappears:

broken — fix it

This should print all five titles in order. It prints three — "Dawn" and "Glow" are lost when the second list runs out.

Comparisons stop the moment either list empties — at most n + m − 1 of them:

What does this print?
def merge_comparisons(a, b):
    i = j = count = 0
    while i < len(a) and j < len(b):
        count += 1
        if a[i] <= b[j]:
            i += 1
        else:
            j += 1
    return count

print(merge_comparisons([1, 2, 3], [4, 5, 6]))
Scene 1 of 8
Project context and further resources
You're building a piece ofTunebox — search & charts
This piece — merge_libraries(): Merges two sorted libraries into one.
Scenario A listener signs in on a new laptop: the phone library and the laptop library are each sorted A→Z. Tunebox merges the two fronts in one pass instead of sorting everything again.
merge_libraries.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
merge_libraries(a, b) → listOne A→Z list with every title from both sorted libraries.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.