Binary search in PHP using divide and conquer algorithm (recursively)

The binary search algorithm is a half-interval search algorithm that finds the position of a specified keyword within a sorted array.

As the sub-problem of a binary search can be solved using iterative or recursive approaches, the recursive approach will be applied to solve the binary search. Following is the recursive approach of depicting binary search algorithm:
function binarySearch($sourceArr, $keyword, $start, $end)
{
  if ($start > $end)
    return 'Your keyword is not found.';

  $middle = ($start + $end) / 2;

  if($keyword == $sourceArr[$middle])
    return $middle;

  elseif($keyword < $sourceArr[$middle])
    return binarySearch($sourceArr, $keyword, $start, $middle - 1);

  else
    return binarySearch($sourceArr, $keyword, $middle + 1, $end);
}

$sourceArr = range(1, 100, 7);
$keyword   = $sourceArr[array_rand($sourceArr)];
$position  = binarySearch($sourceArr, $keyword, 0 , count($sourceArr) - 1);
print_r($sourceArr);
echo ($position >= 0) ? 'Keyword ' . $keyword . ' is found at position: ' . $position :  'Your keyword is not found.';
The output of the above recursive binary search algorithm is:

Output

Array
(
    [0] => 1
    [1] => 8
    [2] => 15
    [3] => 22
    [4] => 29
    [5] => 36
    [6] => 43
    [7] => 50
    [8] => 57
    [9] => 64
    [10] => 71
    [11] => 78
    [12] => 85
    [13] => 92
    [14] => 99
)
Keyword 15 is found at position: 2

Comments