PHP實現二分法查找

二分查找法須要數組是一個有序的數組。php

<?php
function binarySearch($num, $arr) {
    $start = 0;
    $end = count($arr);
    $mid = floor(($start+$end)/2);

    while ($start<$end-1) {
        if ($num == $arr[$mid]) {
            return $mid;
        } elseif ($num < $arr[$mid]) {
            $end = $mid;
            $mid = floor(($start+$end)/2);
        } else {
            $start = $mid;
            $mid = floor(($start+$end)/2);
        }
    }
    return false;
}
$arr = [1,2,3,4,5,6,7,8,9,10];
$result = binarySearch(7,$arr);
print_r($result);
相關文章
相關標籤/搜索