首页 > 代码库 > php二分查找

php二分查找

<?php
/**
 * 二分查找:查找一个值在数组中的位置
 *@$val:查找的值
 *@$arr:操作的数组,前提是按顺序排列
 */
header("content-type:text/html;charset = utf-8");
function biary_search($arr,$val){
    $num = count($arr);
    $low = 0;
    $high = $num - 1;
    while($low<$high){
        $mid = floor(($high-$low)/2);
        if ($arr[$mid] == $val){
            return $mid;
        }elseif ($arr[$mid]>$val){
            $high = $mid -1;
        }else {
            $low = $mid+1;
        }
    }
    return "not found";
}

$array = array(1,2,3,34,534,754,823,923);
$index = biary_search($array, "34");
echo $index;