Thursday, May 17, 2012

How to Implement Binary Search in Python

My simple implementations of binary search algorithms (iterative and recursive) in Python.

#!/usr/bin/env python

def search(l, i, func):
    lo = 0
    hi = len(l) - 1
    mid = (lo + hi) / 2
    return func(l, i, lo, mid, hi)
    
def recursive_binary_search(l, i, lo, mid, hi):
    if lo > mid or hi < mid: return -1

    if l[mid] > i:
        hi = mid - 1
        mid = (lo + hi) / 2
        return recursive_binary_search(l, i, lo, mid, hi)
    elif l[mid] == i:
        return mid
    elif l[mid] < i:
        lo = mid + 1
        mid = (lo + hi) / 2
        return recursive_binary_search(l, i, lo, mid, hi)

def iterative_binary_search(l, i, lo, mid, hi):
    while lo <= mid and hi >= mid:
        if l[mid] > i:
            hi = mid - 1
            mid = (lo + hi) / 2
        elif l[mid] == i:
            return mid
        elif l[mid] < i:
            lo = mid + 1
            mid = (lo + hi) / 2
    return -1
    
if __name__ == "__main__":
    l = [x for x in xrange(0, 10)]
    print "Using recursive binary search"
    print "Input:", l
    for i in xrange(0, len(l)):
        index = search(l, i, recursive_binary_search)
        print "Searching for", i, ", got index", index
        assert i == index
    i = 10
    index = search(l, i, recursive_binary_search)
    print "Searching for", i, ", got index", index

    print

    print "Using iterative binary search"
    print "Input:", l
    for i in xrange(0, len(l)):
        index = search(l, i, iterative_binary_search)
        print "Searching for", i, ", got index", index
        assert i == index
    i = 10
    index = search(l, i, iterative_binary_search)
    print "Searching for", i, ", got index", index

No comments:

Post a Comment