PHP迴圈實現二分查詢
function search($search, $arr)
{
$start = 0;
$length = count($arr);
while($start < $length - 1 && in_array($search,$arr))
{
$mid = floor(($start+$length)/2);
if($arr[$mid] == $search){
return $mid;
} else if ($arr[$mid] < $search){
$start = $mid + 1;
} else if ($arr[$mid] > $search){
$length = $mid - 1;
}
}
return false;
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結