An Easier Binary Search

Правка en1, от Hastorius, 2025-05-07 07:41:07

So I suck at binary search, and just mess around with +1s until it seems to work, get a WA or two, mess around with more +1s, and occasionally get it right by accident. But while talking to iframe_, I learned about a binary search implementation that is significantly more intuitive, cleaner, and shorter called Bitwise Binary Search. You can probably figure out how it works from just the name. Instead of storing a range with a left and right bound, you store it in a single int(or long). The current range of values in the nth iteration is the 1 through n-1th largest bits in the number to those bits followed by all 1s. This is fairly intuitive, as each binary search iteration will decrease the the search range by half. The first iteration will determine whether the largest bit of the integer is 1 or 0, and depending on which it is, this will limit the range to the bottom or top half. There's a couple of really cool features this has. First of all, it's easy to write:

int v = start;

for(int step = 1<<20; step > 0; step /= 2)
  if(works(v+step)) v += step;

This is clearly a lot shorter than a normal binary search implementation, and the answer will be stored in v. But on top of that, this will, by default, work for both lowerbound and upperbound. It will find the most extreme value that works, whether works returns true for the bottom x values or top x. This is intuitive as well, so implementing it in contest will take minimal time. It can also be very easily adapted to floating point binary search on answers with similar syntax:

float current = start, maxstep = 1e6, minstep = 1e-6;

for(float step = maxstep; step >= minstep; step /= 2)
  if(works(current+step)) current += step;

I finally learned binary search after reaching expert!

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en5 Английский Hastorius 2025-05-07 16:58:54 94
en4 Английский Hastorius 2025-05-07 16:58:02 0 (published)
en3 Английский Hastorius 2025-05-07 16:57:17 98
en2 Английский Hastorius 2025-05-07 07:42:08 52
en1 Английский Hastorius 2025-05-07 07:41:07 1849 Initial revision (saved to drafts)