Skip to content

Commit dc415ec

Browse files
realDuYuanChaogithub-actions
and
github-actions
authored
Added double linear search recursion (TheAlgorithms#2445)
* double linear search recursion * fixup! Format Python code with psf/black push Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent 0dea049 commit dc415ec

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed
+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
def search(list_data: list, key: int, left: int = 0, right: int = 0) -> int:
2+
"""
3+
Iterate through the array to find the index of key using recursion.
4+
:param list_data: the list to be searched
5+
:param key: the key to be searched
6+
:param left: the index of first element
7+
:param right: the index of last element
8+
:return: the index of key value if found, -1 otherwise.
9+
10+
>>> search(list(range(0, 11)), 5)
11+
5
12+
>>> search([1, 2, 4, 5, 3], 4)
13+
2
14+
>>> search([1, 2, 4, 5, 3], 6)
15+
-1
16+
>>> search([5], 5)
17+
0
18+
>>> search([], 1)
19+
-1
20+
"""
21+
right = right or len(list_data) - 1
22+
if left > right:
23+
return -1
24+
elif list_data[left] == key:
25+
return left
26+
elif list_data[right] == key:
27+
return right
28+
else:
29+
return search(list_data, key, left + 1, right - 1)
30+
31+
32+
if __name__ == "__main__":
33+
import doctest
34+
35+
doctest.testmod()

searches/simple_binary_search.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def binary_search(a_list: List[int], item: int) -> bool:
4242
if item < a_list[midpoint]:
4343
return binary_search(a_list[:midpoint], item)
4444
else:
45-
return binary_search(a_list[midpoint + 1:], item)
45+
return binary_search(a_list[midpoint + 1 :], item)
4646

4747

4848
if __name__ == "__main__":

0 commit comments

Comments
 (0)