Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do a "Lazy Binary Search"?

Someone asked about Lazy Binary Searches today. Not knowing what that was, I looked for it, and found this post: What is Lazy Binary Search? Essentially, a Lazy Binary Search is a Binary Search where you compare for inequalities first, and only compare for equality once - at the end.

What's the point? Under what circumstances is checking if A<B easy to do, but checking if A=B is so hard you want to avoid it if possible?

like image 859
zmbq Avatar asked Jun 13 '26 15:06

zmbq


2 Answers

It's one less comparison per iteration.

Of course, that's at the expense of a worse average runtime (you don't get the opportunity to return early).1 But sometimes all you care about is worst-case runtime (consider hard-real-time applications, or a pipelined hardware implementation).


1. Although the asymptotic complexity doesn't change.

like image 146
Oliver Charlesworth Avatar answered Jun 17 '26 20:06

Oliver Charlesworth


One thing the lazy search does is find the first element in the sequence that's equal to the target (assuming the target is in the sequence).

If you have several elements that match the target, a non-lazy search would get you any one of those.

So, the C++ library's binary_search could be implemented as non-lazy (and I imagine it usually is), while lower_bound cannot.

like image 36
Michael Burr Avatar answered Jun 17 '26 20:06

Michael Burr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!