首页 > 其他 > 详细

二分查找

时间:2018-01-07 22:39:45      阅读:248      评论:0      收藏:0      [点我收藏+]

二分查找要求数组必须有序,代码比较容易理解

如下:

# coding: utf-8

arr1 = [0, 1, 3, 5, 7, 8]
item = 3


# non-recurse
def binary_search(alist, aitem):
    n = len(alist)
    start = 0
    end = n - 1
    while start <= end:
        mid = (start + end) // 2
        if alist[mid] == aitem:
            return True
        elif aitem < alist[mid]:
            end = mid - 1
        else:
            start = mid + 1
    return False


print(binary_search(arr1, item))


# recurse
def binary_search_recurse(alist, aitem):
    n = len(alist)
    if n == 0:
        return False
    mid = n // 2
    if aitem == alist[mid]:
        return True
    elif aitem < alist[mid]:
        return binary_search_recurse(alist[:mid], aitem)
    else:
        return binary_search_recurse(alist[mid + 1:], aitem)


print(binary_search_recurse(arr1, item))

二分查找

原文:https://www.cnblogs.com/becker/p/8232493.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!