Average Case Analysis of Quick Sort
Average Case Analysis of Quick Sort
Assume a strategy for choosing pivots such that, after partitioning A into
A1 and A2, all lengths of A1 from 0 to | 𝐴| − 1 are equally likely.
The running time of quickSort equals the time of its two recursive calls
plus time to do the partition.
𝑇 (𝑛) = 𝑇 (𝑖) + 𝑇 (𝑛 − 𝑖) + 𝑐 ⋅ 𝑛
1𝑛 − 1 𝑇 𝑗
𝐸(𝑇 (𝑖)) = 𝑛 � ( )
𝑗 =0
Since 𝑛 − 𝑖 can take on the same values as 𝑖, and all such values are equally
likely,
On average, then
2 ⎛𝑛 − 1 𝑇 𝑗 ⎞ + 𝑐 ⋅ 𝑛
𝑇 (𝑛) = 𝑛 ⎜⎜ � ( )⎟⎟
⎝𝑗 =0 ⎠
Multiply through by 𝑛:
1 of 3 02/12/19, 11:36 am
5. Average Case Analysis of Quick Sort https://secweb.cs.odu.edu/~zeil/cs361/web/webs...
⎛𝑛 − 1 ⎞ 2
𝑛 ⋅ 𝑇 (𝑛) = 2 ⋅ ⎜ � 𝑇 ( 𝑗)⎟ + 𝑐 ⋅ 𝑛
⎜⎝ ⎟⎠
𝑗 =0
𝑛 is just a variable, so this must be true no matter what value we plug in for
it. Try replacing 𝑛 by 𝑛 − 1.
⎛𝑛 − 2 ⎞ 2
(𝑛 − 1) ⋅ 𝑇 (𝑛 − 1) = 2 ⋅ ⎜⎜ � 𝑇 ( 𝑗)⎟⎟ + 𝑐 ⋅ (𝑛 − 1)
⎝𝑗 =0 ⎠
𝑛 −1
= 2 ⋅ ⎛ ∑ 𝑗 = 0 𝑇 ( 𝑗) ⎞ + 𝑐 ⋅ 𝑛
2
𝑛 ⋅ 𝑇 (𝑛)
⎝⎜ ⎟
⎠
𝑛 −2 2
( 𝑛 − 1) ⋅ 𝑇 ( 𝑛 − 1) = 2 ⋅ ⎛ ∑ 𝑗 = 0 𝑇 ( 𝑗) ⎞ + 𝑐 ⋅ ( 𝑛 − 1)
⎝⎜ ⎟
⎠
𝑇 (𝑛 ) 𝑇 (𝑛 − 1 )
𝑛+1 = 𝑛 + 𝑛2𝑐
+1
𝑇 (𝑛 − 1 ) 𝑇 (𝑛 − 2 )
𝑛 = 𝑛−1 + 2𝑐
𝑛
𝑇 (𝑛 − 2 ) 𝑇 (𝑛 − 3 )
𝑛−1 = 𝑛−2 + 𝑛2𝑐
−1
Note that most of the terms on the left will have appeared on the right in the
previous equation, so if we were to add up all these equations, these terms
would appear on both sides and could be dropped:
𝑇 (𝑛) 𝑇 ( 1) 𝑛 +1
= + 2𝑐 � 1
𝑛+1 2 𝑗 =3
𝑗
𝑛 +1 1
As 𝑛 gets very large, � approaches ln (𝑛) + 𝛾, where 𝛾 is Euler's
𝑗 =3 𝑗
constant, 0.577...
2 of 3 02/12/19, 11:36 am
5. Average Case Analysis of Quick Sort https://secweb.cs.odu.edu/~zeil/cs361/web/webs...
Hence
𝑇 (𝑛) 𝑇 ( 1)
= + 2𝑐 ⋅ ln (𝑛) + 2𝑐𝛾 = ln (𝑛) + 𝑐2 = 𝑂( ln (𝑛))
𝑛+1 2
and so
In the Forum:
3 of 3 02/12/19, 11:36 am