Skip to content

Commit 9b5c977

Browse files
authored
refactor(searches): add type annotations, docstring, and doctests to double_linear_search_recursion.py
1 parent f5988cc commit 9b5c977

1 file changed

Lines changed: 40 additions & 26 deletions

File tree

searches/double_linear_search.py

Lines changed: 40 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,51 @@
1-
from __future__ import annotations
1+
"""
2+
Recursive Double Linear Search Algorithm
23
4+
Searches for a target element in a list by recursively checking both ends simultaneously.
5+
"""
36

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:
511
"""
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
716
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.
1122
12-
Examples:
13-
>>> double_linear_search([1, 5, 5, 10], 1)
23+
>>> double_linear_search_recursion([1, 2, 3, 4, 5], 1)
1424
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)
1832
-1
19-
>>> double_linear_search([1, 5, 5, 10], 10)
20-
3
2133
"""
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)
3446

3547

3648
if __name__ == "__main__":
37-
print(double_linear_search(list(range(100)), 40))
49+
import doctest
50+
51+
doctest.testmod()

0 commit comments

Comments
 (0)