In the previous blog post Time complexity and shortcoming of Binary Search, we calculated that approximately the average search length is
Causes of the optimization
1 | template <typename T> |
As shown in the above code, it does 1 successful comparation and goes deep into the left side of
Derivation
Considering the general situation, we can select
Now the question is that what number between
接下来用递推分析法。对于长度为
的有序向量,每一步迭代都有三种可能的分支:
- 经过
次成功的比较,转化为一个规模为 的新问题 - 经过
次失败的比较和 次成功的比较,转化为另一个规模为 的新问题 - 经过
次失败的比较,在当前位置命中
由以上分析可得递推式:
Similarly, we can write down the recurrence formula:
Having had the formula modified:
Using knowledeg of advanced mathmatics, it is calculated that
Therefore, Binary Search can be optimized as Fibonacci Search, which has average search legth of
Implement
1 |
|