03 算法之递归-二分查找法-python实现

二分查找法递归实现

#!python
#coding=utf-8

"""
二分查找法
时间复杂度O(log n)
list 需要查找的list
item 需要查找的元素
"""
def binary_search(list, item):
    low = 0
    high = len(list) - 1
    mid = find_mid(list, low, high, item)
    return mid

def find_mid(list, low, high, item):
    mid = (low + high) / 2
    if low <= high:
        guess = list[mid]
        if guess == item:
            return mid
        elif guess > item:
            high = mid - 1
        else:
            low = mid - 1
    return find_mid(list, low, high, item)

my_list = [10, 20, 30, 50, 80, 90, 100]
print(binary_search(my_list, 80))

执行结果

4

你可能感兴趣的:(python)