Skip to content

Add bin-search implement by recursion #96

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions searches/binary_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,39 @@ def binary_search_std_lib(sorted_collection, item):
return index
return None

def binary_search_by_recursion(sorted_collection, item, left, right):

"""Pure implementation of binary search algorithm in Python by recursion

Be careful collection must be sorted, otherwise result will be
unpredictable
First recursion should be started with left=0 and right=(len(sorted_collection)-1)

:param sorted_collection: some sorted collection with comparable items
:param item: item value to search
:return: index of found item or None if item is not found

Examples:
>>> binary_search_std_lib([0, 5, 7, 10, 15], 0)
0

>>> binary_search_std_lib([0, 5, 7, 10, 15], 15)
4

>>> binary_search_std_lib([0, 5, 7, 10, 15], 5)
1

>>> binary_search_std_lib([0, 5, 7, 10, 15], 6)

"""
midpoint = left + (right - left) // 2

if sorted_collection[midpoint] == item:
return midpoint
elif sorted_collection[midpoint] > item:
return binary_search_by_recursion(sorted_collection, item, left, right-1)
else:
return binary_search_by_recursion(sorted_collection, item, left+1, right)

def __assert_sorted(collection):
"""Check if collection is sorted, if not - raises :py:class:`ValueError`
Expand Down