美文网首页
二分搜索(Binary_Search)

二分搜索(Binary_Search)

作者: chenplus | 来源:发表于2019-03-09 14:42 被阅读0次
1. 二分搜索是什么?

二分搜索(英语:binary search),也叫折半搜索(英语:half-interval search),是一种在有序数组中查找特定元素的搜索算法。所以是用二分查找的前提是数组必须是有序的;时间复杂度,空间复杂度请参照下图;有的同学可能对时间复杂度和空间复杂的计算有点绕,我又在其他文章中介绍;

图片来自wikipedia
2. 下面通过代码讲解,注意了解下注释;

有关算法将基于python编写,如果你是javer,没有关系,你可以看的很轻松。

2.1 while循环方式
# python while循环版
def binary_search(list, item):
    low = 0
    hight = len(list) - 1
    while low <= hight:
        mid = (low + hight)//2  # 双斜线表示取整
        guess = list[mid]       # guess表示我们猜测mid位置即为我们要查找的元素
        if(guess == item):      # 如果我们猜中,返回下表
            return mid
        if(guess < item):       # 如果猜测的值比较小 那么我们从新的将区间定位的较大的区间
            low = mid + 1
        else:
            hight = mid - 1     # 如果猜测的时间比较大,我们把新的区间定位到较小的区间

    return None                 # 未能匹配到值

#test
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(binary_search(my_list, 7))

2.2递归方式
# python 递归版
def binary_search2(low, hight, item, list):
    if(low > hight):
        return -1
    mid = low + (hight - low)//2 # 计算mid值,注意是 hight-low
    guess = list [mid]
    if(guess == item):
        return mid
    if(guess < item):
        return binary_search2(mid+1, hight, item, list) # 
    if(guess > item):
        return binary_search2(low, mid - 1, item, list)

#test
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(binary_search2(0, len(my_list)-1, 7, my_list))
2.3运行结果
image.png

相关文章

  • 二分搜索(Binary_Search)

    1. 二分搜索是什么? 二分搜索(英语:binary search),也叫折半搜索(英语:half-interva...

  • 读书打卡<<算法图解>> day 1

    1 二分查找 针对有序的元素列表 def binary_search(list,item): low = 0 he...

  • 二分查找(C语言)

    二分查找(binary_search) 二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要...

  • Algorithm进阶计划 -- 二分搜索

    二分搜索二分搜索模板二分搜索运用 1. 二分搜索模板 二分搜索(二分查找)也称折半查找(Binary Search...

  • 算法-二分搜索算法

    算法:二分搜索算法(折半查找算法)时间复杂度: 二分搜索算法概述 二分搜索算法伪代码 二分搜索算法实现 二分搜索算...

  • Effective STL 第34条

    为什么有些算法需要排序的区间 binary_search算法是二分查找, 这种查找需要查找空间的序列是有序的. 为...

  • 搜索算法

    顺序搜索 二分搜索

  • AVL 树

    一:什么是 AVL 树? 在我的上一篇文章《二分搜索树与二分查找法》中,详细介绍了二分搜索树这种数据结构。二分搜索...

  • 二分算法-LeetCode 69

    二分算法-LeetCode 69 二分算法 二分算法模板, 二分搜索即搜索一个数,如果存在,返回其索引,否则返回-...

  • Pearls9. 代码调优

    [TOC] 问题:在包含1000个整数的表中进行二分搜索: 二分搜索的调优 说明:在二分搜索中通常不需要代码调优 ...

网友评论

      本文标题:二分搜索(Binary_Search)

      本文链接:https://www.haomeiwen.com/subject/yirjpqtx.html