diff options
Diffstat (limited to 'kohana/helpers/arr.php')
-rw-r--r-- | kohana/helpers/arr.php | 49 |
1 files changed, 20 insertions, 29 deletions
diff --git a/kohana/helpers/arr.php b/kohana/helpers/arr.php index 87f2be1f..9f0dc097 100644 --- a/kohana/helpers/arr.php +++ b/kohana/helpers/arr.php @@ -152,52 +152,43 @@ class arr_Core { } /** - * Binary search algorithm. - * - * @param mixed the value to search for - * @param array an array of values to search in - * @param boolean return false, or the nearest value - * @param mixed sort the array before searching it - * @return integer + * @param mixed $needle the value to search for + * @param array $haystack an array of values to search in + * @param boolean $sort sort the array now + * @return integer|FALSE the index of the match or FALSE when not found */ - public static function binary_search($needle, $haystack, $nearest = FALSE, $sort = FALSE) + public static function binary_search($needle, $haystack, $sort = FALSE) { - if ($sort === TRUE) + if ($sort) { sort($haystack); } - $high = count($haystack); + $high = count($haystack) - 1; $low = 0; - while ($high - $low > 1) + while ($low <= $high) { - $probe = ($high + $low) / 2; - if ($haystack[$probe] < $needle) + $mid = ($low + $high) >> 1; + + if ($haystack[$mid] < $needle) { - $low = $probe; + $low = $mid + 1; + } + elseif ($haystack[$mid] > $needle) + { + $high = $mid - 1; } else { - $high = $probe; + return $mid; } } - if ($high == count($haystack) OR $haystack[$high] != $needle) - { - if ($nearest === FALSE) - return FALSE; - - // return the nearest value - $high_distance = $haystack[ceil($low)] - $needle; - $low_distance = $needle - $haystack[floor($low)]; - - return ($high_distance >= $low_distance) ? $haystack[ceil($low)] : $haystack[floor($low)]; - } - - return $high; + return FALSE; } + /** * Emulates array_merge_recursive, but appends numeric keys and replaces * associative keys, instead of appending all keys. @@ -318,4 +309,4 @@ class arr_Core { return $object; } -} // End arr
\ No newline at end of file +} // End arr |