GPT-OSS 120B × binary-search
8.3Algorithm + full docstring (Args/Returns/Raises + examples)
correctness 9.0quality 8.0documentation 8.03700ms
$ 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
8.3correctness 9.0quality 8.0documentation 8.03700ms
# judge: Correct and clean implementation with proper mid calculation (no overflow issue in Python), but docstring lacks a duplicate-handling example as implied by rubric and adds unrequested TypeError validation not reflected in a raising example.
$ cat gpt-oss-120b.binary-search.r1.response
```python
def binary_search(arr: list[int], target: int) -> int:
"""
Perform a binary search on a sorted list of integers.
Args:
arr (list[int]): A list of integers **already sorted in ascending order**.
target (int): The integer value to search for.
Returns:
int: The index of ``target`` in ``arr`` if it is present; otherwise ``-1``.
Raises:
TypeError: If ``arr`` is not a list or if its elements (or ``target``) are not
integers.
Examples:
>>> binary_search([1, 3, 5, 7, 9], 5)
2
>>> binary_search([2, 4, 6, 8, 10], 1)
-1
>>> binary_search([], 42)
-1
"""
# ---- Input validation ----------------------------------------------------
if not isinstance(arr, list):
raise TypeError("arr must be a list")
if not all(isinstance(x, int) for x in arr):
raise TypeError("all elements of arr must be integers")
if not isinstance(target, int):
raise TypeError("target must be an integer")
# ---- Binary search (iterative) -----------------------------------------
left, right = 0, len(arr) - 1 # search interval [left, right]
while left <= right:
mid = (left + right) // 2 # middle index (floor division)
# Compare the middle element with the target
if arr[mid] == target:
return mid # target found
elif arr[mid] < target:
left = mid + 1 # discard left half (including mid)
else:
right = mid - 1 # discard right half (including mid)
# If we exit the loop, the target is not present in the list
return -1
```
The function uses an **iterative** binary‑search algorithm:
1. Start with the whole list as the search interval (`left = 0`, `right = len(arr)-1`).
2. Repeatedly pick the middle element (`mid`).
3. If the middle element equals the target, return its index.
4. If the middle element is smaller than the target, move the left boundary to `mid + 1`.
5. If the middle element is larger, move the right boundary to `mid - 1`.
6. When the interval becomes empty (`left > right`) the target does not exist, so return `-1`.
The algorithm runs in **O(log n)** time and uses **O(1)** extra space.