实现原理:
二分查找又称折半查找,当所查找的数大于或小于中间数时向相应的方向进行寻找相邻数,将整数据一分为二进行查询从而提高查找效率,需要注意的是在查询前需要将数据依次进行顺序排序才可查询。
<?php
function test_one()
{
$arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
$number = 15;
$len = count($arr);
$high = $len - 1;
$lower = 0;
$data = test_two($arr,$number,$lower,$high);
print_r($data);
}
function test_two(&$arr,$number,$lower,$high)
{
$middle = intval(($lower+$high)/2);
if ($lower > $high){
return -1;
}
if ($number > $arr[$middle]){
return test_two($arr,$number,$middle + 1,$high);
}elseif ($number < $arr[$middle]){
return test_two($arr,$number,$lower,$middle - 1);
}else{
return $middle;
}
}