Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This recursive PHP function is not returning any value [duplicate]

Tags:

php

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);
?>
like image 516
Keir Paesel Avatar asked May 07 '26 21:05

Keir Paesel


1 Answers

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);
        }
    }
}
like image 87
Mark Baker Avatar answered May 10 '26 09:05

Mark Baker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!