首页 > 代码库 > 查找之折半查找

查找之折半查找

前提:查询数组是一个有序数组

算法思想:取middle=(low+high)/2索引的元素值,比较arr[middle]与result, 若查找值result<arr[middle],对low~middle-1进行如上查找,若result>arr[middle],对middle+1~high进行如上查找,如此循环递归,一直到查得或low>high;

代码:

<?php    $arr = array(3,12,44,45,54,232,234,289,322,323,456,554,2323,3432,3435,34454,43546);    function binarySearch(&$arr, $low, $high, $result)    {        if($low>$high)            return "No such digit!";        $middle = round(($low+$high)/2);        if($arr[$middle] == $result)            return $middle;        else if($result <$arr[$middle])            return binarySearch($arr, $low, $middle-1, $result);        else            return binarySearch($arr, $middle+1, $high, $result);    }    echo binarySearch($arr, 0, count($arr)-1, 44);?>

 

查找之折半查找