Python 实现二分查找

"""
二分查找,在有序列表基础上
bisect 模块
"""

# 普通方式
def binary_search(sorted_array, val):
    if not sorted_array:
        return -1

    beg = 0
    end = len(sorted_array) - 1
    while beg <= end:
        mid = int((beg + end)/2)
        if sorted_array[mid] == val:
            return mid
        elif sorted_array[mid] > val:
            end = mid - 1
        else:
            beg = mid + 1
    return -1


# 递归实现二分
def binary_search_recursive(sorted_array, beg, end, val):
    if beg >= end:
        return -1
    mid = int((beg + end) / 2)
    if sorted_array[mid] == val:
        return mid
    elif sorted_array[mid] > val:
        return binary_search_recursive(sorted_array, beg, mid, val)
    else:
        return binary_search_recursive(sorted_array, mid+1, end, val)


print(binary_search_recursive([2,3,4], 0, 3, 4))
posted @ 2021-03-26 21:28  皎然CEO  阅读(220)  评论(0编辑  收藏  举报