二分查找

/**
 * 二分查找(有序序列)
 */

function binaryAlgorithm($list, $item)
{
    $low = 0;
    $high = count($list) - 1;
    while ($low <= $high) {
        $mid = floor($low + $high) / 2;
        $guess = $list[$mid];
        if ($guess == $item) {
            return $mid;
        } elseif ($guess > $item) {
            $high = $mid - 1;
        } else {
            $low = $mid + 1;
        }
    }
    return null;
}

var_dump(binaryAlgorithm([1, 4, 5, 7, 3, 8, 9], 8));

posted @ 2022-03-14 15:09  不当病猫  阅读(18)  评论(0)    收藏  举报