vrijdag 20 november 2009

bin-search for Python

Find function for sorted lists. In a sorted list we can do better than using 'find' which must look at each element in the array in turn. In this function we jump right in the middle of the array. If the middle element is the one we want, we're done. Otherwise, we search in the left or the right half of the vector. This depends on whether the object was less than or greater than the middle element. This example is taken from Paul Graham's 'ANSI Common Lisp', ch 4.

-----------------------
def binSearch(obj, vec):
    l = len(vec)
    if l != 0:
        return finder(obj, vec, 0, l-1)

def finder(obj, vec, start, end):
    r = end - start
    if r == 0:
        if obj == vec[int(start)]:
            return obj
        else:
            return 0
    else:
        mid = start + round(r / 2)
        obj2 = vec[int(mid)]
        if obj < obj2:
            return finder(obj, vec, start, mid-1)
        else:
            if obj > obj2:
                return finder(obj, vec, mid+1, end)
            else:
                return obj

Geen opmerkingen:

Een reactie posten