- floor: documentation ( source)
- ceil: documentation ( source)
- range: documentation ( source)
<?php
$array = range(1,100000); //100k items, ordered.
function searchInArray(array $haystack, $needle) {
$needle = (int)$needle;
$currPos = (int)(count($haystack) / 2);
$topBoundry = count($haystack);
$bottomBoundry = 0;
$moves = 0;
while ($currPos >= $bottomBoundry && $currPos <= $topBoundry) {
$currItem = $haystack[$currPos];
echo "Move: $moves. Current: $currPos:$currItem Searching from $bottomBoundry to $topBoundry\n";
if ($currItem == $needle) {
echo "Found item in $moves moves!";
return $currPos;
}
else if ($currItem > $needle) {
echo "LARGER! Let's go smaller! ";
$topBoundry = $currPos;
$currPos = floor(($currPos+$bottomBoundry)/2);
$moves++;
}
else if ($currItem < $needle) {
echo "SMALLER! Let's go larger! ";
$bottomBoundry = $currPos;
$currPos = ceil(($currPos+$topBoundry)/2);
$moves++;
}
}
}
echo searchInArray($array, 420);