Quick sort Worst case

Quicksort’s performance is dependent on your pivot selection algorithm. The most naive pivot selection algorithm is to just choose the first element as your pivot. It’s easy to see that this results in worst case behavior if your data is already sorted (the first element will always be the min).

There are two common algorithms to solve this problem: randomly choose a pivot, or choose the median of three. Random is obvious so I won’t go into detail. Median of three involves selecting three elements (usually the first, middle and last) and choosing the median of those as the pivot.

Since random number generators are typically pseudo-random (therefore deterministic) and a non-random median of three algorithm is deterministic, it’s possible to construct data that results in worst case behavior, however it’s rare for it to come up in normal usage.

You also need to consider the performance impact. The running time of your random number generator will affect the running time of your quicksort. With median of three, you are increasing the number of comparisons.

Leave a Comment