Intuition. Quicksort's cost is governed by how balanced each partition is. If a median-finding routine of cost is used to choose the pivot, every split produces two halves of size — the best possible recursion tree of depth exactly .
Method. Each recursive call on a subarray of size does two things, then recurses on two halves:
- find the median in to use as the pivot,
- partition around it in .
This gives the recurrence
Since a median needs to read all elements, . Per level the partition work sums to and the median work to , so each of the levels costs . Multiplying:
Worked check. If (linear median, e.g. median-of-medians), then — the optimal comparison-sort bound. If , then .
T(n) = 2*T(n/2) + f(n) + c*n
levels: log n (perfect halving)
per level: O(n + f(n))
=> O((n + f(n)) * log n)
Pitfall: Do not multiply by . The median is computed once per recursive call, not once per element; the (partition) and (median) costs are added at each level, and the comes from the number of levels.