用PHP语言实现二分查找
递归
<?php
/**
* $arr:需要查找的数组
* $min:数组最小下标
* $max:数组最大下标
* $target:要查找的数字
**/
function binarySearch ($arr, $min, $max, $target) {
if ($min <= $max) {
$mid = floor(($min + $max) / 2);
if ($arr[$mid] > $target) {
return binarySearch($arr, $min, $mid - 1, $target);
} elseif ($arr[$mid] < $target) {
return binarySearch($arr, $mid + 1, $max, $target);
} else {
return $mid; #返回目标数字在数组中的下标
}
} else {
return -1; #没找到
}
}
#for循环创建一个待查找的数组
for ($i=1; $i < 10000; $i += 3) {
$arr[] = $i;
}
$res = binarySearch($arr, 0, count($arr)-1, 175);
echo $res;
while循环
<?php
function binarySearch ($arr, $target) {
$min = 0;
$max = count($arr) - 1;
while ($min <= $max) {
$mid = floor(($min + $max) / 2);
if ($arr[$mid] > $target) {
$max = $mid - 1;
} elseif ($arr[$mid] < $target) {
$min = $mid + 1;
} else {
return $mid;
}
}
return -1;
}
#for循环创建一个待查找的数组
for ($i=1; $i < 10000; $i += 3) {
$arr[] = $i;
}
$res = binarySearch($arr, 52);
echo $res;