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.