Integer binary search template

Binary template

  • Algorithm idea: Suppose a target value in a closed interval [l, r], each time interval length is reduced by half, when [l, r]the time, i.e., to find the target.

A template

The interval into [l, mid]and [mid + 1, r]when it is updating operation l = mid + 1or r = mid, without calculation 1 mid.

while (l < r) {
    int mid = l + r >> 1;
    if (check(mid)) r = mid;
    else l = mid + 1;
    return l;
}

Template two

The interval into [l, mid - 1]and [mid, r]when it is update r = mid - 1or l = midadd 1 when calculating mid.

while (l < r) {
    int mid = l + r + 1>> 1;
    if (check(mid)) l = mid;
    else r = mid - 1;
    return l;
}

Guess you like

Origin www.cnblogs.com/clown9804/p/12449217.html