class="php" name="code">** * 二分法查找 * 在有序数组中查询 * * @param int $needle * @param array $arr */ function dichotomize_search($needle, $arr) { $count = count($arr); if ($count < 1) { return false; } if ($count == 1) { if ($count == $needle) { return 0; } else { return false; } } $first = 0; $last = $count - 1; while ($first <= $last) { $mid = floor(($first + $last) / 2); if ($arr[$mid] > $needle) { $last = $mid - 1; } else if ($arr[$mid] < $needle) { $first = $mid - 1; } else { return $mid; } } return false; }
?