递归函数实现:
function binarySearch($arr, $val, $st, $et){ $m_ind = $st + floor(($et-$st)/2); $max_idx = count($arr)-1; $min_idx = 0; if($arr[$min_idx]>$val || $arr[$max_idx]<$val || ($et-$st==1 && $arr[$et]!=$val && $arr[$st]!=$val)){ return -1; } if($arr[$m_ind]==$val){ return $m_ind; } else if($arr[$m_ind] > $val){ $et = $m_ind - 1; return binarySearch($arr, $val, $st, $et); } else { $st = $m_ind + 1; return binarySearch($arr, $val, $st, $et); } }
循环实现:
function binarySearch($arr, $val){ $st = 0; $et = count($arr) - 1; $m_ind = floor(($et-$st)/2); do{ if($arr[$m_ind]==$val){ return $m_ind; } else if($arr[$m_ind] > $val){ $et = $m_ind - 1; $off = ceil(($m_ind-$st)/2); if($off == 0) return -1; $m_ind = $m_ind - $off; } else { $st = $m_ind + 1; $off = ceil(($et-$m_ind)/2); if($off == 0) return -1; $m_ind = $m_ind + $off; } }while(true); }
水平有限,敬请指正!