Transcript
Every sort we've seen so far works by comparing two items at a time. And that sets a speed limit. But there's a way to sort that never compares two items at all, and it slips under the limit. Today: where the limit comes from, and how to dodge it.
Take three items. They could be in six different orders, and a sort has to tell all six apart. Each comparison is a yes-or-no question, so at best it cuts the possibilities in half. Six, three, two, one. That's three comparisons in the worst case. For a thousand items, the limit works out to about eight and a half thousand comparisons. Merge sort, at under nine thousand, is already close to it.
Now a trick that never compares. Say every item is a rating from one to five. Make five boxes, and drop each item into its own box. Just count how many land in each. Then read the boxes out in order. Every item was handled just once, so that's about n steps.
What if the numbers are bigger, say from zero to ninety-nine? Use ten boxes, one per digit. First, sort by the last digit. Then sort again by the first digit, keeping the order from the first round. That's radix sort. It only works because each round is stable, the idea from episode six.
The catch: you need a box for every possible value. That's fine for ratings, ages or digits, but not for just any number at all. So these sorts are for special cases. When all you can do is compare, n log n is the best.
Comparing sorts can't beat n log n. Counting and radix sort dodge the limit by never comparing. Next time, forget sorting altogether: a way to find almost anything in a single step. Hash tables. See you there.
Next episode: hash tables, a way to find almost anything in a single step.