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

Function exponential_search

searches/binary_search.py:360–396  ·  view source on GitHub ↗

Pure implementation of an exponential search algorithm in Python Resources used: https://en.wikipedia.org/wiki/Exponential_search Be careful collection must be ascending sorted otherwise, result will be unpredictable :param sorted_collection: some ascending sorted collection wi

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

Source from the content-addressed store, hash-verified

358
359
360def exponential_search(sorted_collection: list[int], item: int) -> int:
361 """Pure implementation of an exponential search algorithm in Python
362 Resources used:
363 https://en.wikipedia.org/wiki/Exponential_search
364
365 Be careful collection must be ascending sorted otherwise, result will be
366 unpredictable
367
368 :param sorted_collection: some ascending sorted collection with comparable items
369 :param item: item value to search
370 :return: index of the found item or -1 if the item is not found
371
372 the order of this algorithm is O(lg I) where I is index position of item if exist
373
374 Examples:
375 >>> exponential_search([0, 5, 7, 10, 15], 0)
376 0
377 >>> exponential_search([0, 5, 7, 10, 15], 15)
378 4
379 >>> exponential_search([0, 5, 7, 10, 15], 5)
380 1
381 >>> exponential_search([0, 5, 7, 10, 15], 6)
382 -1
383 """
384 if list(sorted_collection) != sorted(sorted_collection):
385 raise ValueError("sorted_collection must be sorted in ascending order")
386 bound = 1
387 while bound < len(sorted_collection) and sorted_collection[bound] < item:
388 bound *= 2
389 left = bound // 2
390 right = min(bound, len(sorted_collection) - 1)
391 last_result = binary_search_by_recursion(
392 sorted_collection=sorted_collection, item=item, left=left, right=right
393 )
394 if last_result is None:
395 return -1
396 return last_result
397
398
399searches = ( # Fastest to slowest...

Callers

nothing calls this directly

Calls 1

Tested by

no test coverage detected