二分查找
- 使用PHP描述顺序查找和二分查找(也叫做折半查找)
自定义区间二分查找
function bin_sch($array, $low, $high, $k){ if ($low <= $high){ $mid = intval(($low+$high)/2); if ($array[$mid] == $k) { return $mid; }elseif ($k < $array[$mid]) { return bin_sch($array, $low, $mid-1, $k); }else{ return bin_sch($array, $mid+1, $high, $k); } } return -1; }
全区间二分查找
function getNum($num, $arr) { $length = count($arr); $start = 0; $end = $length - 1; while ($start <= $end) { $middle = floor(($start + $end) / 2); echo 'start = '.$start.' and end = '.$end.' middle = '.$middle."\n"; sleep(1); if ($arr[$middle] == $num) { return $middle; } if ($arr[$middle] < $num) { $start = $middle + 1; } else { $end = $middle - 1; } } return false; }
来源:https://www.cnblogs.com/mxyindex/p/11050997.html