美文网首页
利用Python写二分查找算法

利用Python写二分查找算法

作者: 万越天 | 来源:发表于2017-10-12 10:42 被阅读0次
    #!/usr/bin/env python
    # _*_ encoding:utf-8 _*_
    
    def binary_search(list,item):
        low = 0
        high = len(list)-1
        while low<=high:
            mid = (low+high)//2   # python2: mid = (low+high)/2
            print(mid)
            guess = list[mid]
            if guess>item:
                high = mid-1
            elif guess<item:
                low = mid+1
            else:
                return mid
        return None
    mylist = [1,3,5,7,9,10,11,13]
    print(binary_search(mylist,5))
    

    相关文章

      网友评论

          本文标题:利用Python写二分查找算法

          本文链接:https://www.haomeiwen.com/subject/yqynyxtx.html