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.