Iterative binary search in Python

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

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

Leave a comment

Your email address will not be published. Required fields are marked *