A Median-Of-Three Killer Sequence
November 8, 2016
In two previous exercises we’ve been working toward a variant of quicksort that has guaranteed O(n log n) performance; there is no quadratic worst case. Before we do that, however, it is instructive to look at the case where our optimized median-of-three version of quicksort fails. Consider this sequence, due to David Musser:
1 11 3 13 5 15 7 17 9 19 2 4 6 8 10 12 14 16 18 20
At the first partitioning, the pivot element will be the median of 1, 2 and 20, which is 2, and the only two elements that change will be 2 and 11, with the partition point after the 2, indicated by the vertical bar:
1 2 | 3 13 5 15 7 17 9 19 11 4 6 8 10 12 14 16 18 20
At the next step, the pivot element will be the median of 3, 4 and 20, which is 4, and again the partition will advance only by two:
1 2 3 4 | 5 15 7 17 9 19 11 13 6 8 10 12 14 16 18 20
And so on. Each partition contributes the least possible amount toward the solution, and the time complexity becomes quadratic.
Your task is to write a program that creates a “killer sequence” for the median-of-three partition, then compare its time to the time required for sorting a random partition. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.