数据科学家成长之旅

关注 机器学习,深度学习,自然语言处理,数学

查找算法(1)——二分查找


__author__ = 'steven'

list = [1, 3, 6, 7, 9, 13, 15, 26, 33, 45]

def bin_search(num, list):
    lenth = len(list)
    start = 0
    end = lenth -1
    middle = int(( start + end) / 2)

    if lenth < 0:
        return "error"

    while start <= end:
        if num == list[middle]:
            return middle
        elif num > list[middle]:
            start = middle + 1
        else:
            end = middle - 1

        middle = int(( start + end) / 2)

    return "cannot find your number"

print(bin_search(15, list))

posted on 2017-03-04 20:23  会飞的蝸牛  阅读(316)  评论(0编辑  收藏  举报

导航