binary search DEMO

来源:互联网 发布:鹿晗经纪公司 知乎 编辑:程序博客网 时间:2024/06/05 08:33
#quote from MIT 'introduction to computation and programming using python, Revised'def search(L, e):    """Assumes L is a list, the elements of which are in          ascending order.       Returns True if e is in L and False otherwise"""    def bSearch(L, e, low, high):        #Decrements high - low        if high == low:            return L[low] == e        mid = (low + high)//2        if L[mid] == e:            return True        elif L[mid] > e:            if low == mid: #nothing left to search                return False            else:                return bSearch(L, e, low, mid-1)        else:            return bSearch(L, e, mid + 1, high)    if len(L) == 0:        return False    else:        return bSearch(L, e, 0, len(L) - 1)


L = [1, 2, 10, 8, 0, 100, 23, 89, 6]


L.sort()


search(L, 8)
Out[121]: True


search(L, 4)
Out[122]: False

0 0
原创粉丝点击