Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

binary search recursive

"""Binary Search
Recursive
	- 2 Separate functions
    	--> Perhaps more readable?
    - Or just one function that recursively calls itself
		--> Perhaps more logical?
"""

## With 2 separate functions
def bin_recur(lst, item):
    return go_bin_recur(lst, item, 0, len(lst) - 1)
    
def go_bin_recur(lst, item, low, high):
    if low <= high:
        mid = (low + high) // 2
        if item > lst[mid]: # To the left
            low = mid + 1 
        elif item < lst[mid]: # To the right
            high = mid - 1
        else: # Found
            return mid
        return go_bin_recur(lst, item, low, high)
    return [] # Not found


## With one function
def bin_recur(lst, item, low=0, high=None):
    if high is None:
        high = len(lst) - 1
    if low <= high:
        mid = (low + high) // 2
        if item > lst[mid]: # To the left
            low = mid + 1 
        elif item < lst[mid]: # To the right
            high = mid - 1
        else: # Found
            return mid
        return bin_recur(lst, item, low, high)
    return [] # Not found

"""Whats your preference?"""
Source by softhunt.net #
 
PREVIOUS NEXT
Tagged: #binary #search #recursive
ADD COMMENT
Topic
Name
2+8 =