有序数组的二分查找


<?php
function bin_search($arr, $low, $height, $target)
{
    if ($low <= $height) {
        $mid = intval(($low + $height) / 2);

        if ($arr[$mid] == $target) {
            return true;
        } else if ($arr[$mid] > $target) {
            return bin_search($arr, $low, $mid - 1, $target);
        } else {
            return bin_search($arr, $mid + 1, $height, $target);
        }
    }

    return false;

}

$arr = [1, 9, 12, 39, 45, 90, 120];

$ret = bin_search($arr, 0, 6, 39);
var_dump($ret);

posted @ 2017-10-06 14:58  Thomas_188  阅读(183)  评论(0编辑  收藏  举报