[英]Asymptotic growth rate of running time of BinarySearch
In the following pseudo code for binarySearch 在下面的binarySearch伪代码中
myfunction(A[1],A[2]..A[n]:array of ints,x:positive integer){
i = 1
j = n
while i<=j do
k=floor( (i+j)/2)
if (x==A[k])
return k;
else if (x<A[k])
j=k-1
else
i=k+1
return -1
}
Why is this inequality true j-i+1 <= n / 2^t
where t
is the number of iterations. 为什么不等式为真j-i+1 <= n / 2^t
,其中t
是迭代次数。 All I get is that n /2^t
with t increasing if n/2^t =1
then t will be the total number of iterations but the Left handed side : i-j+1
I don't get how we connect these statements to make inequality.What is the logic behind? 我得到的是,如果n/2^t =1
则n /2^t
随着t的增加,则t将是迭代的总数,但左手边: i-j+1
我不知道我们如何连接这些造成不平等的陈述。背后的逻辑是什么?
j-i+1
is at any point in time the number of values still to consider. j-i+1
在任何时间点都是要考虑的值的数量。 It is clear that the inequality holds at the beginning: n-1+1 = n / 2^0
. 显然,不等式在开始时成立: n-1+1 = n / 2^0
。
Now with each iteration you approximately half the interval to be searched. 现在,每次迭代您大约要搜索间隔的一半。 A careful analysis of the different cases shows the interval is even reduced a bit more than that. 对不同情况的仔细分析显示,间隔甚至比该间隔减少了一点。 So each iteration gives you at least another factor of 1/2 for the interval size. 因此,每次迭代至少为间隔大小提供另一个1/2的因数。
I will just do one case and leave the other three as exercise for you. 我只做一个案例,剩下的三个作为练习。 Assume j-i+1
is equal to s
and assume s
is an odd number. 假设j-i+1
等于s
并假设s
为奇数。 Then i+j
is even and k=(i+j)/2
points exactly to the middle element leaving (s-1)/2
elements to the left of it and to the right of it. 然后i+j
是偶数,并且k=(i+j)/2
精确指向中间元素,而(s-1)/2
元素在其左侧和右侧。 Lets assume now x < A[k]
so that we will set j
to k-1
. 现在假设x < A[k]
以便将j
设置为k-1
。 The new value of j-i+1
is therefore k-1-i+1 = ki = (s-1)/2 < s/2
. 因此, j-i+1
的新值是k-1-i+1 = ki = (s-1)/2 < s/2
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.