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

Can Sorting Beat n log n? Counting and Radix Sort

Pressing play loads the video from YouTube.

Every sort 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 at all, and it slips under the limit.
We see where the limit comes from (three items have six possible orders, and each comparison can at best cut the possibilities in half), sort ratings by simply counting them into boxes, sort two-digit numbers in two rounds with radix sort, and look at the catch: you need a box for every possible value.

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

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.

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