<?php
class Binary
{
private $executions = 0;
private $type = '';
//二分查找法
public function binSearch($arr, $search)
{
$this->type = '非递归二分查找法';
$height = count($arr)-1;
$low = 0;
while ($low <= $height) {
$this->executions++;
//获取中间数
$mid = floor(($low + $height) / 2);
// 判断当这个值等于寻找的那个值后直接返回
if ($arr[$mid] == $search) {
return $mid;
//当中间值小于所查值时,则$mid左边的值都小于$search,此时要将$mid赋值给$low
} elseif ($arr[$mid] < $search) {
$low = $mid + 1;
//中间值大于所查值,则$mid右边的所有值都大于$search,此时要将$mid赋值给$height
} elseif ($arr[$mid] > $search) {
$height = $mid-1;
}
}
return "查找失败";
}
//顺序查找
public function seqSearch($arr, $k)
{
$this->type = '顺序查找';
foreach ($arr as $key => $val) {
$this->executions++;
if ($val == $k) {
return $key;
}
}
return "查找失败";
}
public function getCount()
{
return $this->type.' 执行了 '.$this->executions.' 次';
}
}
$binary = new Binary;
<?php
require_once 'binary.php';
$arr = [1,2,3,4,5,6,7,8,9,10,11,12];
echo $binary->binSearch($arr, 19) ."\n";
echo $binary->getCount();
先把源码贴出来,然后在解析它
其实在经过几次debug你就可以发现,其实这边最重要的一个数值就是mid这个中间数
1.会先把中间数求出来
2.然后这个中间数会以索引值的形式存在
3.判断第一次这个索引值跟需要搜索的那个值是否相等
4.判断数组的这个中间数为索引的值是否比查询的小,如果小的话那就说明,这个中位数的索引的值 左侧都会小于这个搜索的值
5.判断数组的这个中间数为索引的值如果比查询的值大,那就说明这个中间数为索引的右侧都会比查询的这个值大
注意点:变量low跟height