PHP二分查找算法
程序员文章站
2024-03-17 16:00:10
...
二分查找法
<?php
//循环方式
function binary($arr, $low, $top, $target) {
while ($low <= $top) {
$mid = floor(($low + $top) / 2);
if ($arr[$mid] == $target) {
return $mid;
} elseif($arr[$mid] < $target) {
$low = $mid + 1;
} else {
$top = $mid - 1;
}
}
return -1;
}
$arr = array(1,3,9,23,54);
echo binary($arr, 0, count($arr), 9);
//递归方式
function binaryRecursive($arr, $low, $top, $target) {
if ($low <= $top) {
$mid = floor(($low + $top) / 2);
if ($arr[$mid] == $target) {
return $mid;
} elseif ($arr[$mid] < $target) {
$low = $mid + 1;
return binaryRecursive($arr, $low, $top, $target);
} else {
$top = $mid - 1;
return binaryRecursive($arr, $low, $top, $target);
}
} else {
return -1;
}
}
$arr = array(1,3,9,23,54);
echo binaryRecursive($arr, 0, count($arr), 9);