二分查找法需要数组是一个有序的数组。
<?php
function binarySearch($num, $arr) {
$start = 0;
$end = count($arr);
$mid = floor(($start+$end)/2);
while ($start<$end-1) {
if ($num == $arr[$mid]) {
return $mid;
} elseif ($num < $arr[$mid]) {
$end = $mid;
$mid = floor(($start+$end)/2);
} else {
$start = $mid;
$mid = floor(($start+$end)/2);
}
}
return false;
}
$arr = [1,2,3,4,5,6,7,8,9,10];
$result = binarySearch(7,$arr);
print_r($result);