|
1 | | -from __future__ import annotations |
| 1 | +""" |
| 2 | +Recursive Double Linear Search Algorithm |
2 | 3 |
|
| 4 | +Searches for a target element in a list by recursively checking both ends simultaneously. |
| 5 | +""" |
3 | 6 |
|
4 | | -def double_linear_search(array: list[int], search_item: int) -> int: |
| 7 | + |
| 8 | +def double_linear_search_recursion( |
| 9 | + sequence: list[int], target: int, start: int = 0, end: int | None = None |
| 10 | +) -> int: |
5 | 11 | """ |
6 | | - Iterate through the array from both sides to find the index of search_item. |
| 12 | + Recursively searches for target in sequence from both ends. |
| 13 | +
|
| 14 | + Time Complexity: O(n) |
| 15 | + Space Complexity: O(n) due to recursive call stack |
7 | 16 |
|
8 | | - :param array: the array to be searched |
9 | | - :param search_item: the item to be searched |
10 | | - :return the index of search_item, if search_item is in array, else -1 |
| 17 | + :param sequence: A list of integers. |
| 18 | + :param target: The integer value to search for. |
| 19 | + :param start: Starting index for search window. |
| 20 | + :param end: Ending index for search window. |
| 21 | + :return: Index of target if found, else -1. |
11 | 22 |
|
12 | | - Examples: |
13 | | - >>> double_linear_search([1, 5, 5, 10], 1) |
| 23 | + >>> double_linear_search_recursion([1, 2, 3, 4, 5], 1) |
14 | 24 | 0 |
15 | | - >>> double_linear_search([1, 5, 5, 10], 5) |
16 | | - 1 |
17 | | - >>> double_linear_search([1, 5, 5, 10], 100) |
| 25 | + >>> double_linear_search_recursion([1, 2, 3, 4, 5], 5) |
| 26 | + 4 |
| 27 | + >>> double_linear_search_recursion([1, 2, 3, 4, 5], 3) |
| 28 | + 2 |
| 29 | + >>> double_linear_search_recursion([1, 2, 3, 4, 5], 6) |
| 30 | + -1 |
| 31 | + >>> double_linear_search_recursion([], 3) |
18 | 32 | -1 |
19 | | - >>> double_linear_search([1, 5, 5, 10], 10) |
20 | | - 3 |
21 | 33 | """ |
22 | | - # define the start and end index of the given array |
23 | | - start_ind, end_ind = 0, len(array) - 1 |
24 | | - while start_ind <= end_ind: |
25 | | - if array[start_ind] == search_item: |
26 | | - return start_ind |
27 | | - elif array[end_ind] == search_item: |
28 | | - return end_ind |
29 | | - else: |
30 | | - start_ind += 1 |
31 | | - end_ind -= 1 |
32 | | - # returns -1 if search_item is not found in array |
33 | | - return -1 |
| 34 | + if end is None: |
| 35 | + end = len(sequence) - 1 |
| 36 | + |
| 37 | + if start > end: |
| 38 | + return -1 |
| 39 | + |
| 40 | + if sequence[start] == target: |
| 41 | + return start |
| 42 | + if sequence[end] == target: |
| 43 | + return end |
| 44 | + |
| 45 | + return double_linear_search_recursion(sequence, target, start + 1, end - 1) |
34 | 46 |
|
35 | 47 |
|
36 | 48 | if __name__ == "__main__": |
37 | | - print(double_linear_search(list(range(100)), 40)) |
| 49 | + import doctest |
| 50 | + |
| 51 | + doctest.testmod() |
0 commit comments