NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior1 view

Implement binary search on a sorted array.

Practice

AI answer

For an array sorted in ascending order, binary search takes O(log n) time and O(1) additional space. The function returns the index of the found element or -1; if there are duplicates, it may return any matching index.

function binarySearch(array $items, int $target): int
{
    $left = 0;
    $right = count($items) - 1;

    while ($left <= $right) {
        $mid = $left + intdiv($right - $left, 2);

        if ($items[$mid] === $target) {
            return $mid;
        }

        if ($items[$mid] < $target) {
            $left = $mid + 1;
        } else {
            $right = $mid - 1;
        }
    }

    return -1;
}

This assumes the array has contiguous indexes, is sorted in ascending order, and that the values and target are integers.