KonkurStudy
همه کارت‌ها

Median-Pivot Quicksort Recurrence

Picking the exact median as pivot gives a perfectly balanced split, yielding T(n)=2T(n/2)+f(n)+Θ(n)=O((n+f(n))log⁡n)T(n)=2T(n/2)+f(n)+\Theta(n)=O((n+f(n))\log n).

کارت فرمول کنکور ارشد علوم کامپیوتر

اهمیت
۰/۵

Intuition. Quicksort's cost is governed by how balanced each partition is. If a median-finding routine of cost f(n)f(n) is used to choose the pivot, every split produces two halves of size n/2n/2 — the best possible recursion tree of depth exactly log⁡n\log n.

Method. Each recursive call on a subarray of size mm does two things, then recurses on two halves:

  • find the median in f(m)f(m) to use as the pivot,
  • partition around it in Θ(m)\Theta(m).

This gives the recurrence

T(n)=2 T(n/2)+f(n)+Θ(n).T(n) = 2\,T(n/2) + f(n) + \Theta(n).

Since a median needs to read all elements, f(n)=Ω(n)f(n)=\Omega(n). Per level the partition work sums to Θ(n)\Theta(n) and the median work to O(f(n))O(f(n)), so each of the log⁡n\log n levels costs O(n+f(n))O(n+f(n)). Multiplying:

T(n)=O((n+f(n))log⁡n).T(n) = O\big((n+f(n))\log n\big).

Worked check. If f(n)=Θ(n)f(n)=\Theta(n) (linear median, e.g. median-of-medians), then T(n)=O((n+n)log⁡n)=O(nlog⁡n)T(n)=O((n+n)\log n)=O(n\log n) — the optimal comparison-sort bound. If f(n)=n2f(n)=n^2, then T(n)=O(n2log⁡n)T(n)=O(n^2\log n).

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 nn by f(n)f(n). The median is computed once per recursive call, not once per element; the nn (partition) and f(n)f(n) (median) costs are added at each level, and the log⁡n\log n comes from the number of levels.

فرمول‌های کلیدی

Median-pivot recurrence
T(n)=2 T(n/2)+f(n)+Θ(n)T(n) = 2\,T(n/2) + f(n) + \Theta(n)

Balanced split from using the true median as pivot, plus median cost f(n) and linear partition cost.

Closed-form running time
T(n)=O((n+f(n))log⁡n)T(n) = O\big((n + f(n))\log n\big)

Per-level cost O(n+f(n)) times the log n levels of perfect halving.

#quicksort#median#pivot-selection#recurrence#divide-and-conquer

سوالات تمرینی