All episodes · From a List to Your Map App · Episode 7

Merge Sort: Split, Sort, Merge

Pressing play loads the video from YouTube.

Sorting a thousand items by hand took up to half a million comparisons. Merge sort needs fewer than ten thousand. The trick: split the list in half, and in half again, then merge the pieces back together in order.
We learn the key move (merging two sorted rows), split eight items all the way down and merge them back up, see why that adds up to n log n, and find out how the same idea sorts data too big to fit in memory: external sorting.

Every animation in this video is drawn by code, and the narration is an AI voice.

Transcript

Sorting a thousand items by hand took up to half a million comparisons. This method needs fewer than ten thousand. The trick: don't sort the whole list at once. Split it in half, and in half again, until every piece is a single item. Then put the pieces back together, in order. Today: merge sort.

Start with the key move. Here are two rows that are already sorted. Compare the two front items. Take the smaller one, and repeat. Each comparison places one item into the result. When one row runs out, the rest of the other just slides in. Eight items, at most seven comparisons.

Now the whole method. Split eight items into halves, then quarters, then single items. A single item is already sorted. Then merge back up: pairs, then fours, then all eight. This is divide and conquer: split a big problem into smaller copies of itself, solve those, and combine the answers.

Why is it fast? Each level of merging touches every item once: about n steps. And halving eight down to one takes just three levels. That's log base two of n. So the total is about n times log n. For a thousand items, fewer than ten thousand comparisons, instead of half a million.

The price is memory. Merging needs a second row, as big as the first. But the same idea can sort data too big to fit in memory at all. Sort one chunk at a time, and write it back to the disk, then merge the sorted chunks, reading just a little from each one. That's called external sorting.

Merge sort: split until it's trivial, then merge, always in n log n time. Next time, a sort that's usually even faster in practice, and needs no extra row. Quicksort. See you there.

Next episode: quicksort, usually even faster in practice, and it needs no extra row.

Buy the Developer a Coffee

Entirely up to you: it works the same either way.

Every cup turns into the next update.

WeChat Pay QR code
WeChat Pay
Alipay QR code
Alipay
PayPal QR code
PayPal