Recursive binary search in Python


2013-01-12

This is a recursive binary search algorithm in Python.

def binary_search(the_array, the_key, imin, imax):
    if (imax < imin):
        return None
    else:
        imid = imin + ((imax - imin) / 2)
        if the_array[imid] > the_key:
            return binary_search(the_array, the_key, imin, imid-1)
        elif the_array[imid] < the_key:
            return binary_search(the_array, the_key, imid+1, imax)
        else:
            return imid

You might also be interested in the iterative algorithm for binary search in Python.