Home > Backend Development > PHP Tutorial > 一个用PHP代码写的2分查找程序

一个用PHP代码写的2分查找程序

WBOY
Release: 2016-06-13 13:22:32
Original
952 people have browsed it

一个用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."
";
?>
求大神指点我为什么得不出我想要的结果,程序哪里有问题?

------解决方案--------------------
没有返回递归调用时的返回值

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){
      $heigh = $mid - 1 ;
      return BinSearch($a, $low, $heigh, $key);//还有这里
    }
    return null;
  }    
} <div class="clear">
                 
              
              
        
            </div>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template