Main.RecursiveBinarySearch History

Hide minor edits - Show changes to markup

March 09, 2010, at 12:31 PM MST by 10.84.44.129 -
Added lines 1-28:

(:source lang=python:)

"""Recursive version of binary_search"""

def binary_search(a, value) :

    """Returns the index of an occurrence of the given
    value in the given array, or -1 if not found."""
    return binary_search_helper(a, value, 0, len(a) - 1)
  1. Recursive helper to implement search.

def binary_search_helper(a, value, left, right) :

    if (left > right) :
        return -1   # not found
    else :
        mid = (left + right) / 2
        if (a[mid] == value) :
            return mid   # found it!
        elif (a[mid] < value) :
            # middle element too small; search right half
            return binary_search_helper(a, value, mid+1, right)
        else :
            # middle element too large; search left half
            return binary_search_helper(a, value, left, mid-1)

print binary_search(range(10000), 20) print binary_search(range(1, 100, 2), 20)

(:sourceend:)