Created
April 23, 2015 10:30
-
-
Save you-think-you-are-special/5fc9d31323c89174346f to your computer and use it in GitHub Desktop.
Binary Search
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(array $searchArray, $needle) | |
{ | |
$length = count($searchArray); | |
$centerKey = (int)($length / 2); | |
$currentKey = $centerKey; | |
$start = 0; | |
$end = $length - 1; | |
while (isset($searchArray[$currentKey])) { | |
$center = $searchArray[$currentKey]; | |
if ($center === $needle) { | |
return $currentKey; | |
} elseif ($needle < $center) { | |
$end = $currentKey - 1; | |
} else { | |
$start = $currentKey + 1; | |
} | |
$currentKey = (int)(($end - $start) / 2) + $start; | |
}; | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment