Php function returns no value
I am trying to do a simple binary search. I expect this function to return "false" or "true", but it doesn't seem to return anything. I've tried returning integers or strings, just to see if it returns a different datatype, but it doesn't seem to be the case. What am I doing wrong?
<?php
function binarySearch($item, $first, $last){
$numbers=array(3, 5, 9, 11, 17, 24, 38, 47, 50, 54, 57, 59, 61, 63, 65);
if ($first>$last){
return false;
}
else {
$middle=($first+$last)/2;
$middle=(int)$middle;
if ($item==$numbers[$middle]){
echo "found the correct value<br/>";
return true;
}
elseif ($item<$numbers[$middle]){
binarySearch($item, $first, $middle-1);
}
else {
binarySearch($item, $middle+1, $last);
}
}
}
$n=$_GET['txtTarget'];
$first=$_GET['txtFirst'];
$last=$_GET['txtLast'];
echo "the return value is: " . binarySearch($n, $first, $last);
? >
+3
source to share
2 answers
Your recursive calls to binarysearch should return the response from this call, backup the call stack to the binarySearch function ($ item, $ first, $ last) {
$numbers=array(3, 5, 9, 11, 17, 24, 38, 47, 50, 54, 57, 59, 61, 63, 65);
if ($first>$last){
return false;
}
else {
$middle=($first+$last)/2;
$middle=(int)$middle;
if ($item==$numbers[$middle]){
echo "found the correct value<br/>";
return true;
}
elseif ($item<$numbers[$middle]){
return binarySearch($item, $first, $middle-1);
}
else {
return binarySearch($item, $middle+1, $last);
}
}
}
+3
source to share