I'm trying a simple binary search. I expect this function to return 'false' or 'true', but it does not seem to return anything. I tried returning integers or strings, just to see if it would return another datatype, but it did not seem to do so. 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);
?>
Your recursive calls to binarysearch should return the response from that call back up the call stack:
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]){
return binarySearch($item, $first, $middle-1);
}
else {
return binarySearch($item, $middle+1, $last);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With