Created
January 16, 2018 21:01
-
-
Save CaroManel/ec6dc0537a2a6c0683fba9512a68514b to your computer and use it in GitHub Desktop.
Binary Search Iterative
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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