平均时间复杂度
nT(n)=⎣⎢⎢⎢⎢⎢⎢⎢⎢⎢⎡T(0)+T(n−1)+cn+T(1)+T(n−2)+cn+⋮+T(n−1)+T(0)+cn⎦⎥⎥⎥⎥⎥⎥⎥⎥⎥⎤=[T(0)+T(1)+⋯+T(n−1)]+[T(n−1)+T(n−2)+⋯+T(0)]+cn2=2合并[T(0)+T(1)+⋯+T(n−1)]+cn2=2j=0∑n−1T(j)+cn2
根据 nT(n)可知
(n−1)T(n−1)=2j=0∑n−2T(j)+c(n−1)2
用 nT(n) - (n - 1)T(n - 1) 去掉求和公式
nT(n)−(n−1)T(n−1)=2j=0∑n−1T(j)+cn2−2j=0∑n−2T(j)−c(n−1)2=2T(n−1)+cn2−(cn2−2cn+c)=2T(n−1)+2cn−c
把 (n - 1)T(n - 1) 移到右侧去
nT(n)=2T(n−1)+2cn−c+(n−1)T(n−1)=[2−(n−1)]T(n−1)+2cn−c=(n+1)T(n−1)+2cn−c
把 n 移到右侧去
T(n)=n(n+1)T(n−1)+2cn−c=n(n+1)T(n−1)+2c−cn1
两侧同除 n + 1
n+1T(n)nT(n−1)n−1T(n−2)4T(3)3T(2)=nT(n−1)+2cn+11−cn(n+1)1=n−1T(n−2)+2cn1−c(n−1)n1=n−2T(n−3)+2cn−11−c(n−2)(n−1)1⋮=3T(2)+2c41−c3×41=2T(1)+2c31−c2×31
将上面的公式左右相加
==n+1T(n)+nT(n−1)+n−1T(n−2)+⋯+3T(2)(nT(n−1)+n−1T(n−2)+⋯+3T(2)+2T(1))+2c(n+11+n1+⋯+31)−c(n(n+1)1+(n−1)n1+…2×31)(nT(n−1)+n−1T(n−2)+⋯+3T(2)+2T(1))+2c(n+11+n1+⋯+31)−c(n(n+1)1+(n−1)n1+…2×31)
合并同类项
n+1T(n)===2T(1)+2c(n+11+n1+⋯+31)−c(n(n+1)1+(n−1)n1+…2×31)2T(1)+2c[(n1+⋯+31+21+1)−(n+11+21+1)]−c[(n(n+1)1+(n−1)n1+⋯+2×31+1×21)−1×21]2T(1)+2c[(lnn+0.577+2n1)−(n+11+21+1)]−c(1−n+11−1×21)
去掉常数项
n+1T(n)T(n)≈lnn≈(n+1)lnn≈nlogn
附录:
调和级数
1+21+31+⋯+n1=k=1∑nn1=lnk+γ+2k1≈lnk+0.577+2k1
https://zh.wikipedia.org/wiki/调和级数#发散率
==1×21+2×31+⋯+n(n+1)1+(n−1)n1(11−21)+(21−31)+⋯+(n−11−n1)+(n1−n+11)1−n+11
参考
https://en.wikipedia.org/wiki/Quicksort
Quick-analysis
如何证明快速排序法的平均复杂度为 O(nlogn)? - 知乎
https://www.quora.com/What-is-the-sum-of-the-series-1+-1-2-+-1-3-+-1-4-+-1-5-up-to-infinity-How-can-it-be-calculated