<?php
// PHP 二分查找
function search($arr, $sea){
$low = 0; // 确定数组的开始的下标
$len = count($arr)-1; // 确定数组的最后一下标 数组的长度-1
//echo $len; exit;
while( $low <= $len ) {
// 向下取整 2.9 => 2
$num = floor(($low + $len) / 2);
//echo $num; echo "<br><br><br>";
// 中间元素 和 要查询的比较大小
// 判读是否是中间的那为数 是 返回
if($arr[$num] == $sea){
return $num;
}
// 中间元素比目标大,查找左部
if($arr[$num] > $sea){
$len = $num - 1;
//echo $len; echo "<br>";
}
// 中间元素比目标小,查找右部
if($arr[$num] < $sea) {
$low = $num + 1;
//echo $low; echo "<br>";
}
}
return false;
}
//使用二分式算法查找数据
$arr = array(1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29);
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
$sch['1'] = search($arr, 27); // 结果 13
// $num = 7
// $arr['7'] = 15 < 27 $low = 8; $num = (8 + 14)/2 = 11
// $arr['11'] = 23 < 27 $low = 12; $num = (12 + 14)/2 = 13
// $arr['13'] = 27 = 27
$sch['2'] = search($arr, 17); // 结果 8
// $num = 7
// $arr['7'] = 15 < 17 $low = $num + 1 = 8; $num = (8 + 14)/2 = 11
// $arr['11'] = 23 > 17 $len = $num - 1 = 10; $num = (8 + 10)/2 = 9
// $arr['9'] = 19 > 17 $len = $num - 1 = 8; $num = (8 + 8 )/2 = 8
// $arr['8'] = 17 = 17
var_dump($sch); // array(2) { [1]=> float(13) [2]=> float(8) }
?>