程序猿阵线联盟-汇总各类技术干货程序员

二分查找法(Python)

2018-04-10  本文已影响0人  import_hello

在 Python 中分别用循环和递归两种方式来实现二分查找法

本文的最新版本位于:https://github.com/iwhales/algorithms_notes
转载请注明出处:https://www.jianshu.com/u/5e6f798c903a

# -*- coding: utf-8 -*-
# 二分查找的时间复杂度是math.log(n,2)


def binary_search_loop(a_list: list, item: int):
    """
    循环方式
    :param a_list: 有序列表
    :param item: 被查找的目标项
    :return: 如果a_list中包含item,返回item的索引值,否则返回None
    """
    low = 0
    high = len(a_list) - 1
    while low <= high:
        mid = (low + high) // 2
        guess = a_list[mid]
        if guess == item:
            return mid
        elif guess > item:
            high = mid - 1
        else:
            low = mid + 1
    return None


def binary_search_recursive(a_list: list, item: int):
    """
    递归方式
    :param a_list: 有序列表
    :param item: 被查找的目标项
    :return: 如果a_list中包含item,返回item的索引值,否则返回None
    """
    mid = (len(a_list) - 1) // 2
    if len(a_list) == 1:
        if item == a_list[0]:
            return 0
        else:
            return None
    if item == a_list[mid]:
        return mid
    elif item > a_list[mid]:
        index = binary_search_recursive(a_list[mid + 1:], item)
        if index is None:
            return None
        return mid + 1 + index
    else:
        index = binary_search_recursive(a_list[:mid], item)
        return index


if __name__ == '__main__':
    my_list = [1, 2, 3, 4]
    assert binary_search_loop(my_list, 1) == 0
    assert binary_search_loop(my_list, 2) == 1
    assert binary_search_loop(my_list, 3) == 2
    assert binary_search_loop(my_list, 4) == 3
    assert binary_search_loop(my_list, 10) is None

    assert binary_search_recursive(my_list, 1) == 0
    assert binary_search_recursive(my_list, 2) == 1
    assert binary_search_recursive(my_list, 3) == 2
    assert binary_search_recursive(my_list, 4) == 3
    assert binary_search_recursive(my_list, 10) is None
上一篇下一篇

猜你喜欢

热点阅读