查詢之折半查詢

風痕影默發表於2014-12-09

前提:查詢陣列是一個有序陣列

演算法思想:取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);
?>

 

相關文章