Skip to content

Instantly share code, notes, and snippets.

@CaroManel
Created January 16, 2018 19:18
Show Gist options
  • Save CaroManel/a5a498e1b8b3b26b7c2e314f198f3b07 to your computer and use it in GitHub Desktop.
Save CaroManel/a5a498e1b8b3b26b7c2e314f198f3b07 to your computer and use it in GitHub Desktop.
Binary Search Recursive
<?php
function binarySearchRecursion($array, $find, $left, $right)
{
if ($left > $right) {
return -1;
}
$middle = floor( ($left + $right) / 2 );
if ($find === $array[$middle]) {
return $middle;
} elseif ($find < $array[$middle]) {
return binarySearchRecursion($array, $find, $left, $middle-1);
}
return binarySearchRecursion($array, $find, $middle+1, $right); // our key might be in the right sub-array
}
$array = [2,4,5,7,8,13,14,15,26,27,29,31,44,45,46,66,67,68,69,71,80];
$find = 8;
$result = binarySearchRecursion($array, $find, 0, count($array) -1);
echo "found in $result";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment