Skip to content

Commit

Permalink
Add bin-search implement by recursion
Browse files Browse the repository at this point in the history
  • Loading branch information
ZivLi committed Jul 5, 2017
1 parent d4d56a6 commit 23ac6bc
Showing 1 changed file with 33 additions and 0 deletions.
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

0 comments on commit 23ac6bc

Please sign in to comment.