1. 程式人生 > >php迴圈實現折半查詢

php迴圈實現折半查詢

<?php     function binarySearch($arr, $num){         $left = 0;         $right = count($arr) - 1;

        while($left <= $right){             $mid = intval(($left + $right) / 2);

            if($arr[$mid] == $num){                 return $mid;             }

            if($num > $arr[$mid]){                 $left = $mid + 1;             } else {                 $right = $mid - 1;             }         }

        return -1;     }

    $array = array('6','16','24','36','50','54','72','96','97','103','148','150','153','169','173','194','200','201','202','203','204','215','231','243','245','247','251','258','261','264','297','320','328','332','333','337','339','354','360','361','384','387','390','421','427','430','476','480','481','482','498','513','517','520','534','544','546','547','554','557','562','582','585','586','590','606','625','627','641','645','657','658','663','674','678','698','705','709','716','740','746','757','806','838','841','858','879','885','922','948','952','968','981','985','988','998');

    $ret = binarySearch($array, 200);     var_dump($array[$ret]); ?>