A very minor correction to hielsnoppe's answer:
In an n
-element array (n > 0
), the element to compare is at index m = floor((n-1)/2)
. So there are three possibilities
A[m] < K
, then after one comparison, the search continues in an n-1-m = ceiling((n-1)/2)
-element array.
A[m] > K
, then after two comparisons, the search continues in an m
-element array.
A[m] == K
, then we're done after two comparisons.
So if we denote the maximal (worst-case) number of comparisons for a search in an n
-element array by C(n)
, we have
C(0) = 0
C(n) = max { 1 + C(ceiling((n-1)/2), 2 + C(floor((n-1)/2) }, n > 0
For odd n = 2k+1
, the floor and ceiling are identical, so the maximum is evidently the latter,
C(2k+1) = 2 + C(k)
and for even n = 2k
, we find
C(2k) = max { 1 + C(k), 2 + C(k-1) }.
For n = 2
, that resolves to C(2) = 1 + C(1) = 1 + 2 = 3
, for all larger even n
, the maximum is 2 + C(k-1)
, since for n >= 1
we have C(n) <= C(n+1) <= C(n) + 1
.
Evaluating the recursion for the first few n
, we find
C(0) = 0
C(1) = 2
C(2) = 3
C(3) = C(4) = 4
C(5) = C(6) = 5
C(7) = C(8) = C(9) = C(10) = 6
C(11) = ... = C(14) = 7
C(15) = ... = C(22) = 8
C(23) = ... = C(30) = 9
So by induction we prove
C(n) = 2k, if 2^k <= n+1 < 2k + 2^(k-1), and
C(n) = 2k+1, if 2^k + 2^(k-1) <= n+1 < 2^(k+1)
or
C(n) = 2*log2(n+1) + floor(2*(n+1)/(3*2^floor(log2(n+1)))).
This is an exact upper bound.