Skip to content

Instantly share code, notes, and snippets.

@CaroManel
Created January 16, 2018 22:16
Show Gist options
  • Save CaroManel/e0ec41f6a2f281eed5eb178d441acdb7 to your computer and use it in GitHub Desktop.
Save CaroManel/e0ec41f6a2f281eed5eb178d441acdb7 to your computer and use it in GitHub Desktop.
Exponential Search
<?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
}
function exponentialSearch($array, $find)
{
$size = count($array);
if ($size == 0) {
return -1;
}
$bound = 1;
while ($bound < $size && $array[$bound] < $find) {
$bound *= 2;
}
return binarySearchRecursion($array, $find, $bound/2, min($bound, $size));
}
$array = [2,4,5,7,8,13,14,15,26,27,29,31,44,45,46,66,67,68,69,71,80];
$find = 71;
$result = exponentialSearch($array, $find);
echo "Found $find at index $result";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment