您的位置:首页 > 其它

binary search DEMO

2015-07-09 08:55 309 查看
#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: