PHP Binary Search - Recursive and non-recursive sample code sharing
<?php function binarySearch($arr, $val) { $len = count($arr); if(!is_array($arr) || $len <= 0){ return false; } if($val < $arr[0] || $val > $arr[$len-1]){ return false; } $start = 0; $end = $len - 1; while($start <= $end){ $mid = intval(( $end+$start )/2); //中间值 if($arr[$mid] == $val){ return $mid; } if($val < $arr[$mid]){ $end = $mid - 1; }else{ $start = $mid + 1; } } return false; }
RecursiveImplementation:
<?php // 递归 function binarySearch_r($arr, $low, $high, $key) { $len = count($arr); if(!is_array($arr) || $len <= 0){ return false; } if($key < $arr[0] || $key > $arr[$len-1]){ return false; } if($low <= $high){ $mid = intval( ($low+$high)/2 ); if($arr[$mid] == $key){ return true; } $func_name = FUNCTION; if($key < $arr[$mid]){ return $func_name($arr, $low, $mid-1, $key); } else{ return $func_name($arr, $mid+1, $high, $key); } } return false; }
The above is the detailed content of PHP binary search-recursive and non-recursive sample code sharing. For more information, please follow other related articles on the PHP Chinese website!