|
| 1 | +""" |
| 2 | +Pure Python implementation of Recursive Binary Search. |
| 3 | +
|
| 4 | +Binary Search is a divide-and-conquer algorithm that works on sorted lists. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | +from typing import Sequence, TypeVar |
| 9 | + |
| 10 | +T = TypeVar("T") |
| 11 | + |
| 12 | + |
| 13 | +def binary_search_recursive( |
| 14 | + arr: Sequence[T], |
| 15 | + target: T, |
| 16 | + left: int = 0, |
| 17 | + right: int | None = None, |
| 18 | +) -> int: |
| 19 | + """ |
| 20 | + Perform recursive binary search on a sorted sequence. |
| 21 | +
|
| 22 | + :param arr: A sorted sequence of comparable elements |
| 23 | + :param target: The element to search for |
| 24 | + :param left: Left boundary of the search interval |
| 25 | + :param right: Right boundary of the search interval |
| 26 | + :return: Index of target if found, otherwise -1 |
| 27 | +
|
| 28 | + >>> binary_search_recursive([1, 2, 3, 4, 5], 3) |
| 29 | + 2 |
| 30 | + >>> binary_search_recursive([1, 2, 3, 4, 5], 1) |
| 31 | + 0 |
| 32 | + >>> binary_search_recursive([1, 2, 3, 4, 5], 5) |
| 33 | + 4 |
| 34 | + >>> binary_search_recursive([1, 2, 3, 4, 5], 6) |
| 35 | + -1 |
| 36 | + >>> binary_search_recursive([], 10) |
| 37 | + -1 |
| 38 | + >>> binary_search_recursive([2, 4, 6, 8], 6) |
| 39 | + 2 |
| 40 | + """ |
| 41 | + |
| 42 | + if right is None: |
| 43 | + right = len(arr) - 1 |
| 44 | + |
| 45 | + if left > right: |
| 46 | + return -1 |
| 47 | + |
| 48 | + mid = left + (right - left) // 2 |
| 49 | + |
| 50 | + if arr[mid] == target: |
| 51 | + return mid |
| 52 | + if arr[mid] > target: |
| 53 | + return binary_search_recursive(arr, target, left, mid - 1) |
| 54 | + return binary_search_recursive(arr, target, mid + 1, right) |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == "__main__": |
| 58 | + import doctest |
| 59 | + |
| 60 | + doctest.testmod() |
0 commit comments