Binary Search Implementation
Intermediate
25 XP
You're trying this as a guest: your result shows here but isn't saved.
Sign in
Implement binary search from scratch — the algorithm that makes searching sorted data lightning fast (O(log n) vs O(n)).
Write a function binary_search(arr, target) that:
- Takes a sorted list and a target value.
- Returns the index of the target if found.
- Returns -1 if the target is not in the list.
Do not use Python's in operator, .index(), or bisect module.
Test your function with the provided test calls.
To pass
- Find 7 in the middle of the array
- Find 1 at the start of the array
- Find 13 at the end of the array
- Return -1 when target is not in array
- Return -1 for empty array
Need a hint?
- Use two pointers: low=0, high=len(arr)-1. Loop while low <= high.
- Calculate mid = (low + high) // 2, then compare arr[mid] to target.
- If arr[mid] < target, search the right half (low = mid + 1). If >, search left (high = mid - 1).