Binary Search Featured Training

First, the binary search template

A template

public binarySearch() {
    while(left < right) {
        mid = (right - left) >>> 1;
        if(check(mid)) {
            left = mid + 1;
        }else {
            right = mid;
        }
    }
}

Template two

public binarySearch() {
    while(left < right) {
        mid = (right - left + 1) >>> 1;
        if(check(mid)) {
            right = mid - 1;
        }else {
            left = mid;
        }
    }
}

 explain:

①while(left < right)

Find the end of this condition is left == right, you do not need to return to tangle left or right. If the title is intended to illustrate the binary search must answer, you can return directly; if a binary search may not be the answer, only need to make a few at the end like a judge.

② preparative median

mid = (rigth - left) >>> 1 unsigned right shift of the benefits of using

Faster than a displacement operator division performed

b unsigned right shift at high bit 0, is removed in division when it is possible to get the correct answer

Additional information:

Left: Low 0 up;

Logical shift right (unsigned shift right): 0 high fill;

Arithmetic right shift (Signed right): High fill the symbol bit

③ When writing branch, priority would like to write you can eliminate mid, it is difficult to think direct else

Note that the left take the median mid = (right - left) >>> 1 corresponds to the left = mid + 1;

Take and median mid = (right - left + 1) >>> 1 to the corresponding right = mid - 1;

This can effectively avoid an endless loop.

 

Guess you like

Origin www.cnblogs.com/mgblogs/p/11712490.html