Reputation: 4803
I am reading Section 9.3 of Jon Bentley's Programming Pearls, 2nd Edition.
On page 94, Jon gave an implementation of an improved binary search algorithm, utilizing the fact that n is 1000 (search 1000 numbers to find the target).
At the end of the program, it is:
if p > 1000 || x[p] != t
p = -1
My question is that, what if p is exactly 1000? It seems like the when p is 1000, it should also error out, like:
if p >= 1000 || x[p] != t
p = -1
Anyway, this part of code is translated from the code on page 93, at the end of wich:
if p >= n || x[p] != t
p = -1
Is my understanding correct? I am just wondering if this is a typo, or it is really not necessary to include the case p is 1000 in the condtion.
Another question is, in lines 5~6 from bottom up on page 94, it says: When the first test fails and l stays zero, the program computes the bits of p in order, most significant bit first.
What does it mean here? And when the first test fails, shoudn't l be -1, rather than 0?
Anyone can elaborate on this statement?
P.S. I can't find Jon's email address, otherwise, I'll field these questions to him. :-(
Upvotes: 2
Views: 357
Reputation: 80287
It is typo. Maxvalue of l is 999 (1000 - 512 + 256 + .. + 1, ), so maxvalue of p = l+1 is 1000. It is clear for hardcoded version of binsearch (listing 9.8).
And we can see real C code (not pseudocode) here (Alg.4) with if (p >= n ||
Upvotes: 3