二分查找法(Python)

在 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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 〇、前言 本文共108张图,流量党请慎重! 历时1个半月,我把自己学习Python基础知识的框架详细梳理了一遍。 ...
    Raxxie阅读 19,023评论 17 410
  • http://python.jobbole.com/85231/ 关于专业技能写完项目接着写写一名3年工作经验的J...
    燕京博士阅读 7,615评论 1 118
  • 体育之星 体育方面有特长,热心体育活动推广发展,能够带动和影响周围同学参与体育活动,积极参加校内外各项运动比赛,...
    hiahiaheng阅读 484评论 0 0
  • 那一句话,给了我莫大的鼓舞,那是一次考试结束,我考的十分不理想,心情十分难过,在家里,爸爸并没有说什么。 ...
    逍尘阅读 247评论 0 1
  • 女一:沈曦若 男一:叶黎君 女二:王诗涵 男二:颜黎川
    情殇u阅读 187评论 0 0