Playground
Model Configuration
System Prompt
Stop Sequences
Human:
\n\n
###
Prompt
Ready
Completion
347 tokens · 1.2s
from typing import List, Optional
def binary_search(
arr: List[int],
target: int
) -> Optional[int]:
"""
Perform binary search on a sorted array.
Args:
arr: Sorted list of integers
target: Value to search for
Returns:
Index of target if found, None otherwise
Raises:
TypeError: If inputs are not of expected types
ValueError: If array is empty
"""
if not isinstance(arr, list):
raise TypeError("Expected a list")
if not arr:
raise ValueError("Array cannot be empty")
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return None
# Example usage
sorted_array = [1, 3, 5, 7, 9, 11, 15, 23]
result = binary_search(sorted_array, 7)
print(f"Found at index: {result}")
# Output: Found at index: 3