Skip to content

Instantly share code, notes, and snippets.

@sayopaul
Created July 2, 2019 14:37
Show Gist options
  • Save sayopaul/55c09ed297a1a9271eef341f51c3b3de to your computer and use it in GitHub Desktop.
Save sayopaul/55c09ed297a1a9271eef341f51c3b3de to your computer and use it in GitHub Desktop.
Binary search PHP implementation
<?php
function binarySearch($list,$itemToBeFound){
$firstIndex = 0;
$lastIndex = (count($list) - 1);
$found = false;
while($firstIndex <= $lastIndex && $found == false){
$midpoint = floor(($firstIndex + $lastIndex) / 2);
if ($itemToBeFound == $list[$midpoint]){
$found = true;
}else{
if($itemToBeFound < $list[$midpoint]){
$lastIndex = $midpoint - 1;
}else if($itemToBeFound > $list[$midpoint]){
$firstIndex = $midpoint + 1;
}
}
}
return $found;
}
//tests the function above
$founded = binarySearch([0, 1, 2, 8, 13, 17, 19, 32, 42],19);
var_dump($founded);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment