Binary search 01. Basic binary search and its variants

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=Binary search and its common variants


table of Contents


Basic binary search

We assume that the data size is n, and the data will be reduced to half of the original after each search, that is, it will be divided by 2. In the worst case, it will not stop until the search interval is reduced to empty.

It can be seen that this is a geometric sequence. When n/2 k =1, the value of k is the total number of reductions. And each reduction operation only involves the size comparison of two data, so after k times of interval reduction operations, the time complexity is O(k). By n/2 k =1, we can find k=log 2 n, so the time complexity is O(logn).

<?php
function bsearch($arr,$n){
    $low=0;
    $high=count($arr)-1;
    //注意边界
    while($low<=$high){
//        $mid=intval(($low+$high)/2);
        $mid=$low+(($high-$low)>>1);
        if($arr[$mid]==$n){
            return $mid;
        }elseif($n<$arr[$mid]){  //n在 [low,mid-1]
            $high=$mid-1;
        }else{  //n 在[mid+1,high]
            $low=$mid+1;
        }
    }
    return -1;
}

Three points that are easy to make mistakes

1. Loop exit condition

Note that it is low<=high, not low

Guess you like

Origin blog.51cto.com/huangkui/2677730