Skip to content

Commit 64bef60

Browse files
reinhold-bcclauss
andauthored
double_linear_search algorithm (TheAlgorithms#2161)
* linear search iterating from both array sides * Update double_linear_search.py * Update double_linear_search.py * added doctests * updated doctests * Update double_linear_search.py * Update double_linear_search.py * added blank after >>> * made all the requested changes * Update double_linear_search.py * Update double_linear_search.py Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 70cf565 commit 64bef60

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

searches/double_linear_search.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from typing import List
2+
3+
4+
def double_linear_search(array: List[int], search_item: int) -> int:
5+
"""
6+
Iterate through the array from both sides to find the index of search_item.
7+
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
11+
12+
Examples:
13+
>>> double_linear_search([1, 5, 5, 10], 1)
14+
0
15+
>>> double_linear_search([1, 5, 5, 10], 5)
16+
1
17+
>>> double_linear_search([1, 5, 5, 10], 100)
18+
-1
19+
>>> double_linear_search([1, 5, 5, 10], 10)
20+
3
21+
"""
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+
35+
36+
if __name__ == "__main__":
37+
print(double_linear_search(list(range(100)), 40))

0 commit comments

Comments
 (0)