二分查找法

function middle_search($arr, $search){
    if (empty($arr) || empty($search)) {
        return false;
    }

    $left = 0;
    $right = count($arr);
    $result = null;
    while ($left <= $right) {
        $middle = floor(($right + $left) / 2);
        if ($search < $arr[$middle]) {
            $right = $middle;
        } elseif ($search > $arr[$middle]) {
            $left = $middle;
        } else {
            //等于情况下
            $result = $middle;
            break;
        }
        echo "\n left=$left , right=$right";
    }
    if (!is_null($result)) {
        return $result;
    }
    return 'no find';
}

 

posted @ 2018-05-24 17:57  王大西  阅读(83)  评论(0编辑  收藏  举报