for ($i = 0; $i < 30; $i++) {
$arr[$i] = $i;
}
var_dump(BinarySearch($arr, 100, 0, count($arr) - 1));
function BinarySearch ($arr, $searchVal, $leftIndex, $rightIndex) {
if ($rightIndex < $leftIndex) {
return 'ERROR';
}
$midIndex = round(($leftIndex + $rightIndex) / 2);
$midVal = $arr[$midIndex];
if ($searchVal < $midVal) {
BinarySearch($arr, $searchVal, $leftIndex, $midIndex - 1);
} else if ($searchVal > $midVal) {
BinarySearch($arr, $searchVal, $midIndex + 1, $rightIndex);
} else {
return $midIndex;
}
}
代码如上,var_dump出来的结果是空,但是如果把BinarySearch里面的两个return语句改成echo浏览器又能正常输出了,到底是哪出了问题?
回复讨论(解决方案)
function BinarySearch ($arr, $searchVal, $leftIndex, $rightIndex) { if ($rightIndex < $leftIndex) { return 'ERROR'; } $midIndex = round(($leftIndex + $rightIndex) / 2); $midVal = $arr[$midIndex]; if ($searchVal < $midVal) { return BinarySearch($arr, $searchVal, $leftIndex, $midIndex - 1); //这里需要返回 } else if ($searchVal > $midVal) { return BinarySearch($arr, $searchVal, $midIndex + 1, $rightIndex); //这里也需要返回 } else { return $midIndex; }}