Last active
May 29, 2016 08:56
-
-
Save esase/b4fff18246abb336eddd92905fa24b77 to your computer and use it in GitHub Desktop.
Simple binary search [algorithm]
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 | |
$input = [ | |
1, | |
3, | |
5, | |
2, | |
4, | |
6, | |
8, | |
7 | |
]; | |
// sort the array | |
sort($input); | |
/** | |
* Search value | |
* | |
* @param integer $search | |
* @param array $input | |
* @return integer|boolean | |
*/ | |
function searchValue($search, $input) | |
{ | |
$leftBorder = 0; | |
$rightBorder = count($input) - 1; | |
while (true) { | |
$middle = floor(($leftBorder + $rightBorder) / 2); | |
// go down | |
if ($search > $input[$middle]) { | |
$leftBorder = $middle + 1; | |
} | |
else if ($search < $input[$middle]) { | |
// go up | |
$rightBorder = $middle - 1; | |
} | |
else { | |
// we've found the value | |
return $input[$middle]; | |
} | |
if ($leftBorder > $rightBorder || $rightBorder < $leftBorder) { | |
return false; | |
} | |
} | |
} | |
var_dump( searchValue(5, $input) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment