Created
July 2, 2019 14:37
-
-
Save sayopaul/55c09ed297a1a9271eef341f51c3b3de to your computer and use it in GitHub Desktop.
Binary search PHP implementation
This file contains hidden or 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 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