Calculate average runtime of binary search with guarantee that search value is in array

六眼飞鱼酱① 提交于 2020-05-17 05:48:08

问题


I understand that binary search is O(logn) for a sorted array. However, I want to know if it is possible to calculate the average runtime with the guarantee that the search value is in the sorted array. This guarantee gives the binary search a much greater probability of finding the search value in less than logn time.

i.e. there is a 1/n chance of finding it in 1 step, 2/n chance of finding it in the 2nd step and so on.

I'm not sure how to go from this intuition into calculating the average runtime. Any ideas?


回答1:


So the probability of finding it in step i is 2^(i-1). To confirm this is correct, the sum of the probabilities for every step should be equal to 1. So, the summation from i = 1 to logn of 2^(i-1)/n is the equation we get, and that is equal to 1.

The average runtime then is the probability at each step * step #:

Summation from i=1 to logn of i * 2^(i-1)/n

Say n = 16, the average runtime is then 1/16( 1*1 + 2*2 + 3*4 + 4*8) = 3.125 which is less than log16 = 4.



来源:https://stackoverflow.com/questions/49269114/calculate-average-runtime-of-binary-search-with-guarantee-that-search-value-is-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!