Please subscribe to the official Codeforces channel in Telegram via the link https://t.me/codeforces_official. ×

1zaid1's blog

By 1zaid1, history, 20 months ago, In English

I'm referring to this binary search

int L = 0, R = n;
while (L < R) {
    int m = (l+r)/2;
    if (F(m)) {
        L = m+1;
    } else {
        R = m;
    }
} return L;

Why conventional Binary seach sucks:

A. There are multiple potential off-by-one errors in it. B. It looks ugly. C. It's not the most intuitive approach.

My binary search:

int x = 0, j = *closest power of two higher than the desired range length*;
while (j/=2) {
    if (!F(x+j)) x += j;
} return x+1;

The intuition: We have a function F(x) that begins to be satisfied at some point P. We want to identify P. We'll aim to go as close to it as possible without touching it, so we'll jump j steps forward and see if we touch the satasfied region; if we do, we won't jump; if we don't, we will. This will put us one step behind P, so we will just add one.

The picture shows an example where the range is 16 and the function is satisfied when x >= 6. We'll attempt leaping a size 8 jump, but the function will be satisfied at that time, so we won't. Then we'll try a size 4 leap and succeed, and so on. Finally, x = 5 represents the greatest x at which the function is not satisfied.

This method achieves the exact same purpose without any areas for off by one errors and I find it much more intuitive than the standared range binary search.

Full text and comments »

  • Vote: I like it
  • +14
  • Vote: I do not like it