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

Quicksort: Pick a Pivot, Split the Rest

Pressing play loads the video from YouTube.

Pick one tower, put everything shorter on its left and everything taller on its right, and that tower is exactly where it belongs. Do the same to each side, and the whole row is sorted.
We partition twelve towers with two markers that walk in from both ends, see why quicksort works in place and is often the fastest sort in practice, find its one weak spot (an already sorted row with a bad pivot), and fix it by choosing the pivot at random.

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

Transcript

Pick one tower, any tower. Put everything shorter on its left, and everything taller on its right. That tower is now exactly where it belongs. Do the same to each side, and the whole row ends up sorted. Today: quicksort, the sort inside a lot of real software, and its one weak spot.

The chosen tower is called the pivot. Here we take the last one: seven. Two markers start at the two ends. The left one moves right until it finds something taller than the pivot. The right one moves left until it finds something shorter. Both are in the wrong half, so swap them. Then keep going, until the markers cross. Finally, the pivot swaps into the gap between the halves. No extra row needed: it all happens in place.

Now quicksort each side the same way, with its own pivot. The pieces get smaller and smaller, until each is a single tower. On average, that's about n log n steps, like merge sort. In practice it's often the fastest of all. It works in place, and it walks through memory in order, which the cache loves.

But there's a weak spot. Give it a row that's already sorted, and always take the last tower as the pivot. Every pivot is the tallest one left. One side gets everything, the other gets nothing, and each level peels off just one tower. That's about n levels instead of log n. Back to n squared, like sorting by hand.

The fix is simple: pick the pivot at random. Then a bad split at every level is so unlikely that, in practice, it just doesn't happen.

Quicksort: pick a pivot, split around it, and repeat on each side. Next time: can any sort beat n log n? Only if it never compares two items at all. See you there.

Next episode: can any sort beat n log n? Only one that never compares two items.

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