递归二分
<?php
/**
* @param $target 查找目标
* @param $arr 待查找数组
* @param $start 数组起始索引
* @param $end 数组结束索引
* @return String
*/
function BinarySearch($target,$arr,$start,$end){
if ($start>$end){
return "Sorry, No Result!";
}
$mid = intval($start+($end-$start)/2);
if ($target == $arr[$mid])
return $mid;
if ($target<$arr[$mid])
return BinarySearch($target,$arr,$start,$mid-1);
else
return BinarySearch($target,$arr,$mid+1,$end);
}
$arr = [0=>'张三',1=>'李四',2=>'王二',3=>'马志'];
echo BinarySearch('李四',$arr,0,sizeof($arr));
循环二分
<?php
/**
* @param $target 查找目标
* @param $arr 待查找数组
* @return String
*/
function BinarySearch($target,$arr)
{
$start = 0;
$end = count($arr) - 1;
while ($start <= $end)
{
$mid = intval($start + ($end - $start)/2);
if ($target == $arr[$mid])
return $mid;
if ($target < $arr[$mid])
$end = $mid - 1;
else
$start = $mid + 1;
}
return "Sorry, No Resustartt!";
}
$arr = [0=>'张三',1=>'李四',2=>'王二',3=>'马志'];
echo BinarySearch('王二',$arr);
网友评论