# 折半查找平均查找长度推导

《软件设计师教程》里关于折半查找的平均查找长度的计算过程有错字和不够完整的问题。在此详细推导一次。

$ASL_{bs}=\displaystyle\sum_{i=1}^n P_i C_i = \frac{1}{n} \displaystyle\sum_{j=1}^h j\cdot2^{j-1}=\frac{n+1}{n} \log_2(n+1)-1$

$ASL_{bs}=\frac{1}{n}\sum_{j=1}^h j\cdot2^{j-1}$

$S=1\times 2^0+2\times2^1+3\times2^2+\dotsb+h\times2^{h-1} \tag{1}$

$2S=1\times 2^1+2\times2^2+3\times2^3+\dotsb+h\times2^{h} \tag{2}$

(1)-(2)可得

$S-2S=1\times 2^0+(2-1)\times2^1+(3-2)\times2^2+\dotsb+(h-(h-1))\times2^{h-1}-h\times2^h$

$(1-2)S=1-h\cdot2^h+\sum_{i=1}^{h-1}2^i$

\begin{aligned} (1-2)S&=1-h\cdot2^h+\frac{2(1-2^{h-1})}{1-2}\\ (1-2)S&=(1-h)2^h-1 \end{aligned}

$S=(h-1)2^h+1\tag{3}$

\begin{aligned} S&=(log_2(n+1)-1)(n+1)+1\\ &=(n+1)log_2(n+1)-n \end{aligned}

$ASL_{bs}=\frac{1}{n}S=\frac{n+1}{n}log_2(n+1)-1$

$h=\lfloor\log_2(n+1)\rfloor$$r=n-(2^h-1)$$v=n-r$，此时

$ASL_{bs}=\frac{1}{n}\left[\sum_{j=1}^{h}j\cdot2^{j-1}+r(h+1)\right]$

$ASL_{bs}=\frac{1}{n}(v+1)log_2(v+1)-v+\frac{1}{n}r(h+1)\tag{4}$

$ASL=\frac{1}{4}\cdot(1+2+2+3)=2$

posted @ 2021-04-09 02:24  zipeilu  阅读(9)  评论(0编辑  收藏