Skip to content

Instantly share code, notes, and snippets.

@CaroManel
Created January 16, 2018 21:01
Show Gist options
  • Save CaroManel/ec6dc0537a2a6c0683fba9512a68514b to your computer and use it in GitHub Desktop.
Save CaroManel/ec6dc0537a2a6c0683fba9512a68514b to your computer and use it in GitHub Desktop.
Binary Search Iterative
<?php
function binarySearchIterative($list, $find)
{
$left = key($list);
$right = count($list) -1;
while ($left <= $right) {
$mid = floor(($left + $right) / 2);
if ($find == $list[$mid]) {
return $mid;
} elseif ($find > $list[$mid]) {
$left = $mid + 1;
} elseif ($find < $list[$mid] ) {
$right = $mid - 1;
}
}
return -1;
}
$array = [2,4,5,7,8,13,14,15,26,27,29,31,44,45,46,66,67,68,69,71,80];
$find = 69;
$result = binarySearchIterative($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