Reputation: 54074
In WikiPedia article for Binary Search
there is a section called Deferred detection of equality
which presents a somewhat "optimized" version of binary search as follows:
int binary_search(int A[], int key, int imin, int imax)
{
while (imax > imin)
{
int imid = (imin + imax) / 2;
if (A[imid] < key)
imin = imid + 1;
else
imax = imid;
}
if((imax == imin) && (A[imin] == key))
return imin;
else
return KEY_NOT_FOUND;
}
It is claimed that this is a better version than the conventional textbook binary search since the .... algorithm uses only one conditional branch per iteration
Is this true? I mean the if
instructions are translated in CMP
and Branch
instructions in assembly so I can not think how an if-else
is better than an if-else if-else
Is there such a difference that I should take into account in higher level languages? The code of the "deffered" version seems more tight I admin, but are there optimizations or penalties in how you form if-else
statements?
Upvotes: 2
Views: 362
Reputation: 437386
The key concept is that it uses one less conditional per iteration. That is, the equality check has been moved outside the while
loop so that it only runs once, while in the basic version it would need to be checked every time¹.
That said, I 'm not sure if there would actually be a measurable difference when using the optimized form. For example, consider that:
Notes:
¹ Actually it is another condition that doesn't need to be checked when the equality comparison moves out, but conceptually there is no difference.
Upvotes: 3