日期:2014-05-17  浏览次数:20552 次

一个用PHP代码写的二分查找程序
<?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]."<br/>";
// echo "key:".$key."<br/>";
if($key == $a[$mid]){
return $mid;
echo $mid;
}elseif($a[$mid] < $key){
$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."<br/>";
?>
求大神指点我为什么得不出我想要的结果,程序哪里有问题?

------解决方案--------------------
没有返回递归调用时的返回值
PHP code
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){
      $low = $mid + 1;
      return BinSearch($a, $low, $heigh, $key);//这里
    }elseif ($a[$mid] > $key){
      $heigh = $mid - 1 ;
      return BinSearch($a, $low, $heigh, $key);//还有这里
    }
    return null;
  }    
}