MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / double_linear_search

Function double_linear_search

searches/double_linear_search.py:4–33  ·  view source on GitHub ↗

Iterate through the array from both sides to find the index of search_item. :param array: the array to be searched :param search_item: the item to be searched :return the index of search_item, if search_item is in array, else -1 Examples: >>> double_linear_search([

(array: list[int], search_item: int)

Source from the content-addressed store, hash-verified

2
3
4def 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
36if __name__ == "__main__":

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected