Skip to content

Instantly share code, notes, and snippets.

@esase
Last active May 29, 2016 08:56
Show Gist options
  • Save esase/b4fff18246abb336eddd92905fa24b77 to your computer and use it in GitHub Desktop.
Save esase/b4fff18246abb336eddd92905fa24b77 to your computer and use it in GitHub Desktop.
Simple binary search [algorithm]
<?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