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

Function exponential_search

searches/exponential_search.py:60–97  ·  view source on GitHub ↗

Pure implementation of an exponential search algorithm in Python. For more information, refer to: https://en.wikipedia.org/wiki/Exponential_search Be careful: the collection must be ascending sorted, otherwise the result will be unpredictable. :param sorted_collection: som

(sorted_collection: list[int], item: int)

Source from the content-addressed store, hash-verified

58
59
60def exponential_search(sorted_collection: list[int], item: int) -> int:
61 """
62 Pure implementation of an exponential search algorithm in Python.
63 For more information, refer to:
64 https://en.wikipedia.org/wiki/Exponential_search
65
66 Be careful: the collection must be ascending sorted, otherwise the result will be
67 unpredictable.
68
69 :param sorted_collection: some ascending sorted collection with comparable items
70 :param item: item value to search
71 :return: index of the found item or -1 if the item is not found
72
73 The time complexity of this algorithm is O(log i) where i is the index of the item.
74
75 Examples:
76 >>> exponential_search([0, 5, 7, 10, 15], 0)
77 0
78 >>> exponential_search([0, 5, 7, 10, 15], 15)
79 4
80 >>> exponential_search([0, 5, 7, 10, 15], 5)
81 1
82 >>> exponential_search([0, 5, 7, 10, 15], 6)
83 -1
84 """
85 if list(sorted_collection) != sorted(sorted_collection):
86 raise ValueError("sorted_collection must be sorted in ascending order")
87
88 if sorted_collection[0] == item:
89 return 0
90
91 bound = 1
92 while bound < len(sorted_collection) and sorted_collection[bound] < item:
93 bound *= 2
94
95 left = bound // 2
96 right = min(bound, len(sorted_collection) - 1)
97 return binary_search_by_recursion(sorted_collection, item, left, right)
98
99
100if __name__ == "__main__":

Callers 1

Calls 1

Tested by

no test coverage detected