Skip to content
mager-bench1.3

GPT-5.6 Sol × binary-search

9.3

Algorithm + full docstring (Args/Returns/Raises + examples)

correctness 10.0quality 8.0documentation 10.011595ms
$ cat binary-search.prompt — what the model was asked
Implement `binary_search(arr: list[int], target: int) -> int` in Python. It should return the index of target in a sorted list, or -1 if not found. Write a proper docstring with Args, Returns, and Raises sections. Add inline comments explaining the algorithm logic. Include 3 test cases as examples in the docstring.

run 1 of 1

9.3
correctness 10.0quality 8.0documentation 10.011595ms

# judge: The implementation is correct and exceptionally well documented, though full type and sortedness validation makes the overall runtime O(n), undermining binary search's usual O(log n) performance.

$ cat codex-cli/gpt-5.6-sol.binary-search.r1.response
```python
def binary_search(arr: list[int], target: int) -> int:
    """Find a target value in a sorted list using binary search.

    Args:
        arr: A list of integers sorted in ascending order.
        target: The integer to find.

    Returns:
        The index of target if found; otherwise, -1.

    Raises:
        TypeError: If arr is not a list, target is not an integer, or an
            element of arr is not an integer.
        ValueError: If arr is not sorted in ascending order.

    Examples:
        >>> binary_search([1, 3, 5, 7, 9], 5)
        2
        >>> binary_search([1, 3, 5, 7, 9], 4)
        -1
        >>> binary_search([], 10)
        -1
    """
    if not isinstance(arr, list):
        raise TypeError("arr must be a list")
    if not isinstance(target, int):
        raise TypeError("target must be an integer")
    if any(not isinstance(value, int) for value in arr):
        raise TypeError("all elements of arr must be integers")
    if any(arr[i] > arr[i + 1] for i in range(len(arr) - 1)):
        raise ValueError("arr must be sorted in ascending order")

    left, right = 0, len(arr) - 1

    # Repeatedly discard the half that cannot contain the target.
    while left <= right:
        # This form avoids unnecessarily adding the two boundary indices.
        middle = left + (right - left) // 2

        if arr[middle] == target:
            return middle

        # Keep only the right or left half based on the middle value.
        if arr[middle] < target:
            left = middle + 1
        else:
            right = middle - 1

    # The search interval is empty, so the target is absent.
    return -1
```