Skip to content

Instantly share code, notes, and snippets.

@you-think-you-are-special
Created April 23, 2015 10:30
Show Gist options
  • Save you-think-you-are-special/5fc9d31323c89174346f to your computer and use it in GitHub Desktop.
Save you-think-you-are-special/5fc9d31323c89174346f to your computer and use it in GitHub Desktop.
Binary Search
<?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