Create a Python program that implements a binary search on a given array of integers.…
- User
Create a Python program that implements a binary search on a given array of integers. arr = [3, 14, 25, 34, 51, 52, 74]
Assistant
Create a Python program that implements a binary search on a given array of integers. arr = [3, 14, 25, 34, 51, 52, 74]
Problem: Create a Python program that implements a binary search on a given array of integers. arr = [3, 14, 25, 34, 51, 52, 74]
Approach: Complexity
Key considerations:
Analysis & Design Considerations
Imp
Args: arr: Sorted list of integers (ascending order) target: Integer value to search for
Returns: Index of target if
""" if right is None: right = len(arr) - 1
if left > right: return -1
mid = left + (right - left) // 2
Let me implement this solution.
Key Design Decisions
mid = left + (right - left) // 2 prevents integer overflowEdge Cases
def binary_search(arr: list[int], target: int) -> int:
"""
Perform binary search on a sorted array.
Args:
arr: Sorted list of integers (ascending order)
target: Integer value to search for
Returns:
Index of target if found, -1 otherwise
Time: O(log n), Space: O(1)
"""
# Edge case: empty array
if not arr:
return -1
left, right = 0, len(arr) - 1
while left <= right:
# Prevents integer overflow (important in other languages)
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1 # Search right half
else:
right = mid - 1 # Search left half
return -1 # Target not found
def binary_search_recursive(arr: list[int], target: int,
left: int = 0, right: int = None) -> int:
"""
Recursive implementation of binary search.
"""
if right is None:
right = len(arr) - 1
if left > right:
return -1
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search_recursive(arr, target, mid + 1, right)
else:
return binary_search_recursive(arr, target, left, mid - 1)
# ============ DEMONSTRATION ============
if __name__ == "__main__":
arr = [3, 14, 25, 34, 51, 52, 74]
print(f"Array: {arr}")
print(f"Indices: {list(range(len(arr)))}")
print("-" * 40)
# Test cases
test_cases = [
(25, "Middle element"),
(3, "First element"),
(74, "Last element"),
(1, "Not present (smaller)"),
(100, "Not present (larger)"),
(40, "Not present (in range)"),
]
for target, description in test_cases:
result = binary_search(arr, target)
status = f"Found at index {result}" if result != -1 else "Not found"
print(f"Search {target:3d} ({description:22s}): {status}")
# Visualization of search process
print("\n" + "=" * 40)
print("SEARCH TRACE for target = 52:")
print("=" * 40)
def trace_binary_search(arr, target):
left, right = 0, len(arr) - 1
step = 1
while left <= right:
mid = left + (right - left) // 2
print(f"Step {step}: arr[{left}..{right}], mid={mid}, arr[mid]={arr[mid]}")
if arr[mid] == target:
print(f" → FOUND at index {mid}")
return mid
elif arr[mid] < target:
print(f" → {arr[mid]} < {target}, search RIGHT")
left = mid + 1
else:
print(f" → {arr[mid]} > {target}, search LEFT")
right = mid - 1
step += 1
return -1
trace_binary_search(arr, 52)
Array: [3, 14, 25, 34, 51, 52, 74]
Indices: [0, 1, 2, 3, 4, 5, 6]
----------------------------------------
Search 25 (Middle element ): Found at index 2
Search 3 (First element ): Found at index 0
Search 74 (Last element ): Found at index 6
Search 1 (Not present (smaller)): Not found
Search 100 (Not present (larger) ): Not found
Search 40 (Not present (in range)): Not found
========================================
SEARCH TRACE for target = 52:
========================================
Step 1: arr[0..6], mid=3, arr[mid]=34
→ 34 < 52, search RIGHT
Step 2: arr[4..6], mid=5, arr[mid]=52
→ FOUND at index 5
| Operation | Iterative | Recursive |
|---|---|---|
| Time | O(log n) | O(log n) |
| Space | O(1) | O(log n) |
Recommendation: Use iterative version in production for better space efficiency and no risk of stack overflow on large arrays.