Quick Sort

Quick sort is a another recursive algorithm that (usually) works in O(n log n) time. However, it is much less predictable than merge sort. When it works, it works well. But it is also prone to occasionally doing things extremely inefficiently.

It is interesting to contrast merge sort with quick sort:

The partition operation centers around a pivot. Here's how it works:

  1. Usually, the first element is taken to be the pivot.
  2. Then it scans from the left until it finds an element greater than or equal to the pivot.
  3. Next, it scans from the right until it finds an element less than or equal to the pivot.
  4. It then swaps these two elements, and starts scanning again.
  5. Eventually, the scans meet in the middle.
  6. The pivot will be swapped with the element immediately before the meeting point.
When this happens, the following must be true: At this point, the procedure can recurse on the two unsorted regions.

And of course, here it is on a longer data set:

With random data, quick sort will usually come out ahead of the other methods. However, quick sort is the only algorithm here that is actually anti-adaptive. It performs worse on semi-sorted data, as shown here:

This horrible performance means that technically speaking, quick sort must be considered O(n²).

But it gets worse. Because it is recursive, quick sort usuall has a space complexity of O(log n). However, in the semi-sorted case, its space complexity becomes linear: O(n). Thus, when it doesn't perform well, it combines the speed of bubble sort with the space complexity of merge sort: the worst of both worlds.

For these reasons, one common trick is to deliberately shuffle the array before sorting it. This makes it neither adaptive nor anti-adaptive.

Quick sort is also not at all stable: by trading elements around, all ordering among tied elements is completely lost.

Thus, using quick sort is a gamble. When it works, it works extremely well. But when it doesn't, it blows up badly.

Here's everything so far:

On to bogo sort...