How often does the loop repeat?
To answer this question let's go back to the original listing. Remember how this function actually works.
last define our current
search area. Initially, there are last-first items in this area.
The two values first and last define our current search
range. If the value we are looking for is somewhere in the array,
it is going to be at a position
>= first and
< last. So the difference,
last-first, defines how many values we have left in
the search range.
last-first values left in the search
Each time around the loop, we cut this area in half.
We stop when the search area has been reduced to a single item.
Let “n” denote the value of
How many times can we divide n things into 2 equal parts before getting down to only 1?
That's the interesting question!
If I start with, let's say, N things in this array, how many times I keep cutting that search area of N things in half till I get to only a single item? (An item that must be the value we are looking for, if that value is anywhere in the array at all.)
Let's assume for the sake of our argument that N is the power of 2 to start with. So we cut N in half -- we get N/2. Next time we cut that half which makes N/4, then N/8 and then N/16 and so on. And the question is, how often can we keep doing that until we reduce the number down to just 1?
The answer may be a bit clearer if we turn the problem around. Start at 1 and keep doubling until we get N. So we start at 1, 2, 4, … and we keep going until we actually get up to N. The number of steps we did in doubling is same as number of steps when we start at N and kept dividing by 2.
How many steps is that? Well, what power of 2 do we reach when we finally get to N? Suppose we took k steps. Then we are saying that N = 2k. Solving for k, we get k = log N.