搜索常见算法:顺序查找,二分法查找,哈希查找,下面是二分查找的实现方式

# coding:utf-8
# 二分查找的前提:只能对有序列进行查找
def binary_search(alist,item):
    """二分查找---递归实现"""
    n = len(alist)
    if n > 0:
        mid  = n//2
        if item == alist[mid] :
            return True
        elif item < alist[mid]:
            return binary_search(alist[:mid],item)
        else:
            return binary_search(alist[mid+1:], item)
    else :
        return False

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


if __name__ == "__main__":
    a = [1,5,6,10,11,13,18,37,99]
    print(a)
    sorted_list_11 = binary_search(a,1)
    print(sorted_list_11)
    sorted_list_12= binary_search(a, 88)
    print(sorted_list_12)
    sorted_list_21 = binary_search_2(a, 18)
    print(sorted_list_21)
    sorted_list_22 = binary_search_2(a, 88)
    print(sorted_list_22)

# [1, 5, 6, 10, 11, 13, 18, 37, 99]
# True
# False
# (True, 6)
# False