0

I am hoping someone can break something down for me in a way I can digest. I am trying to understand the running time for the median of three partitioning.

  1. What is the goal of median of three partitioning? Is it to eliminate the possibility of selecting the largest / smallest element as the pivot, thus resulting in O(n^2) run time?

  2. What would the run time be of a simple median of three partitioning function? Since there are only 3 possible comparisons, and the comparison operation runs in O(1) time, wouldn't it just be 3O(1) or negligible?

Any assistance would be greatly appreciated. Thus far, I have referenced CLRS and the following three pages for assistance:

artemis
  • 225
  • 4
  • 15

2 Answers2

1

You should not confuse median-of-median algorithm with median-of-3 trick.

The former is $O(n{\rm log}n)$ worst-case time.

Ans. to 1. The latter is still $O(n^2)$ worst-case time but faster in practice due to the low frequency of bad patterns seen in practice. This can be seen by the fact that randomized quicksort is $O(n{\rm log}n)$ expected time.

Ans. to 2. It is $O(n)$. The comparison work is $O(1)$ since there are only $3$ elements involving. After, determine the value of the median of three, you need to partition the array around this value. This takes $O(n)$ time.

Thinh D. Nguyen
  • 2,313
  • 3
  • 24
  • 71
1

When you implement QuickSort, if you could magically pick the median as pivot then you would get minimal number of comparisons. If you manage to pick pivots close to the median, sorting is faster.

The median of three random elements is usually closer to the median of the array than a single random element. Throw three dice repeatedly and write down the medians. You will get 3 and 4 much more often than the other numbers.

gnasher729
  • 32,238
  • 36
  • 56