一个用PHP代码写的二分查找程序
function BinSearch($a,$low,$heigh,$key){
if($low > $heigh){
return null;
}else{
$mid = (int)($low+$heigh)/2;
$mid = ceil($mid);
// echo "a[]:".$a[$mid]."
";
// echo "key:".$key."
";
if($key == $a[$mid]){
return $mid;
echo $mid;
}elseif($a[$mid] $low = $mid + 1;
BinSearch($a, $low, $heigh, $key);
}elseif ($a[$mid] > $key){
$heigh = $mid - 1 ;
BinSearch($a, $low, $heigh, $key);
}
return null;
}
}
$a = array(0,1,2,3,4,5,6,7,8,9);
$key = 3;
$result = BinSearch($a, 0, 9, $key);
echo "result:".$result."
";
?>
求大神指点我为什么得不出我想要的结果,程序哪里有问题?
------解决方案--------------------
没有返回递归调用时的返回值
function BinSearch($a,$low,$heigh,$key){ if($low > $heigh){ return null; }else{ $mid = (int)($low+$heigh)/2; $mid = ceil($mid); if($key == $a[$mid]){ return $mid; echo $mid; }elseif($a[$mid] $key){ $heigh = $mid - 1 ; return BinSearch($a, $low, $heigh, $key);//还有这里 } return null; } } <div class="clear"> </div>