关闭

binary search DEMO

143人阅读 评论(0) 收藏 举报
分类:
#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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:91384次
    • 积分:2930
    • 等级:
    • 排名:第12493名
    • 原创:165篇
    • 转载:108篇
    • 译文:30篇
    • 评论:1条
    文章分类
    最新评论