码迷,mamicode.com
首页 > 其他好文 > 详细

二分查找

时间:2018-01-07 23:33:19      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:print   gpo   数组   star   查找   ==   als   比较   tar   

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

如下:

# 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))

二分查找

标签:print   gpo   数组   star   查找   ==   als   比较   tar   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!