A binary lookup program written in PHP code
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] < $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. "
";
?>
Ask the great God why I do not have the results I want, the program where there is a problem?
------Solution--------------------
return value when recursive call is not returned
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 here ($a [$mid] > $key) {$heigh = $mid-1; Return Binsearch ($a, $low, $heigh, $key);//And here} return null; }}