3

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);
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

2 Answers2

3

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);
        }
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

Your binarySearch function only returns when $first is greater than the $last.

In all other cases it does not return anything.

Put return before the function call in the binarySearch function.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bhavya Shaktawat
  • 2,504
  • 1
  • 13
  • 11