python实现二分查找【面试题详解】【附代码】

今天爱分享给大家带来python实现二分查找【面试题详解】【附代码】,希望能够帮助到大家。


def binary_chop(alist, data):
    """
    非递归解决二分查找
    """
    n = len(alist)
    first = 0
    last = n - 1
    while first <= last:
        mid = (last+first)//2
        if alist[mid] > data:
            last = mid - 1
        elif alist[mid] < data:
            first = mid + 1
        else:
            return True
    return False

def binary_chop2(alist, data):
    """
    递归解决二分查找
    """
    n = len(alist)
    if n < 1:
        return False
    mid = n // 2
    if alist[mid] > data:
        return binary_chop2(alist[0:mid], data)
    elif alist[mid] < data:
        return binary_chop2(alist[mid+1:], data)
    else:
        return True

if __name__ == "__main__":
    lis = [2,4, 5, 12, 14, 23]
    if binary_chop(lis, 12):
        print('ok')
    else:
        print('false')

人已赞赏
Python

Python的单元测试放在哪【面试题详解】

2020-12-28 22:18:12

Python

python如何翻转一个单链表【面试题详解】【附代码】

2020-12-29 17:17:32

'); })();