Пожалуйста, подпишитесь на официальный канал Codeforces в Telegram по ссылке https://t.me/codeforces_official. ×

A superior binary search method

Правка en1, от 1zaid1, 2022-11-07 18:17:30

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.

Теги binary search

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский 1zaid1 2022-11-07 18:17:30 1522 Initial revision (published)