代码:
第一种方法
$arr = [1,3,5,12,34,45,50];
function binary(array &$arr,int $low,int $top,int $target){
while($low<=$top){
$mid = floor(($low+$top)/2);
if($arr[$mid] === $target){
return $mid;
} elseif($arr[$mid]>$target){
$top= $mid-1;
} else if($arr[$mid]<$target){
$low= $mid+1;
}
}
return -1;
}
$arr = [1,3,5,12,34,45,50];
echo binary($arr,0,count($arr),50); //6
第二种方法
function binaryRecursive(array &$arr,int $low,int $top,int $target){
$mid = floor(($low+$top)/2);
if ($arr[$mid]>$target){
return binaryRecursive($arr,$low,$mid-1,$target);
} elseif ($arr[$mid]<$target){
return binaryRecursive($arr,$mid+1,$top,$target);
} else if ($arr[$mid]===$target){
return $mid;
} else {
return -1;
}
}
$arr = [1,3,5,12,34,45,50];
echo binaryRecursive($arr,0,count($arr),50); //6
网友评论