Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions search.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ def linear(data: List[Any], target: Any, comparator: Callable[[Any, Any], bool])
# =====================
@staticmethod
def binary(data: List[Any], target: Any, comparator: Callable[[Any, Any], int]) -> Any:
"""
Performs binary search on a sorted list.

The comparator should return:
- 0 if a == b
- negative if a < b
- positive if a > b
Returns the index of the found element, or -1 if not found.
"""
pass

left, right = 0, len(data) - 1
while left <= right:
mid = (left + right) // 2
cmp_result = comparator(data[mid], target)
if cmp_result == 0:
return mid
elif cmp_result > 0:
right = mid - 1
else:
left = mid + 1
return NotFoundError(target)