// Takes a non associative array and returns the index of the found value. // Otherwise it returns -1. MinIndex and MaxIndex are the lowest and highest // indexes of the array. function BinarySearch($arNumbers, $searchValue) { $min = 0; $max = count($arNumbers) - 1; while ($max >= $min) { $midpoint = intval(($max - $min) / 2 + $min); if ($searchValue > $arNumbers[$midpoint]) { $min = $midpoint + 1; } else if ($searchValue < $arNumbers[$midpoint]) { $max = $midpoint - 1; } else { return $midpoint; } } return -1; }
Posted: March 17, 2023
Return to the snippets listing