From 64bef606b606c3b2e78572b88a78ace41471abc6 Mon Sep 17 00:00:00 2001 From: Reinhold <63191266+reinhold-b@users.noreply.github.com> Date: Sat, 4 Jul 2020 11:23:23 +0200 Subject: [PATCH] double_linear_search algorithm (#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 --- searches/double_linear_search.py | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 searches/double_linear_search.py diff --git a/searches/double_linear_search.py b/searches/double_linear_search.py new file mode 100644 index 000000000..6056f00fc --- /dev/null +++ b/searches/double_linear_search.py @@ -0,0 +1,37 @@ +from typing import List + + +def double_linear_search(array: List[int], search_item: int) -> int: + """ + 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([1, 5, 5, 10], 1) + 0 + >>> double_linear_search([1, 5, 5, 10], 5) + 1 + >>> double_linear_search([1, 5, 5, 10], 100) + -1 + >>> double_linear_search([1, 5, 5, 10], 10) + 3 + """ + # define the start and end index of the given array + start_ind, end_ind = 0, len(array) - 1 + while start_ind <= end_ind: + if array[start_ind] == search_item: + return start_ind + elif array[end_ind] == search_item: + return end_ind + else: + start_ind += 1 + end_ind -= 1 + # returns -1 if search_item is not found in array + return -1 + + +if __name__ == "__main__": + print(double_linear_search(list(range(100)), 40))