首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >二分查找递归实现

二分查找递归实现
EN

Stack Overflow用户
提问于 2013-07-30 23:19:39
回答 3查看 789关注 0票数 0

我正在尝试创建我的二进制搜索的递归版本的实现。这就是我到目前为止所拥有的。有人能帮我吗?我不知道该怎么做。

代码语言:javascript
复制
def binarySearch(searchList, numberSought, low, high):
    if high < low:
        return False
    midpoint = (low + high)//2
    print ("high is index", high)
    print ("low is index", low)
    print ("midpoint is index", midpoint)
    if searchList[midpoint] == numberSought:
        return True
    elif ...

    else:
        ...

mylist = [2, 4, 7, 13, 21, 22, 27, 31, 41, 77, 97, 144, 168]
first = 0
last = len(mylist) - 1
candidate = int(input("Does our list contain the following number? "))
print ("It is ",binarySearch(mylist,candidate,first,last), "that our list contains", candidate)
EN

回答 3

Stack Overflow用户

发布于 2013-07-30 23:23:57

代码语言:javascript
复制
    if searchList[midpoint] == numberSought:
        return True
    elif searchList[midpoint] < numberSought:
        pass # somehow search left of midpoint here
    else: # must have > numberSought
        pass # somehow search right of midpoint here

这有帮助吗?

票数 2
EN

Stack Overflow用户

发布于 2013-07-30 23:28:37

为什么不看看Python bisect module中非递归但规范实现的源代码呢?当然,您必须将while循环转换为递归。

票数 0
EN

Stack Overflow用户

发布于 2013-07-31 01:57:27

你可以使用这个递归程序..执行二进制搜索。

代码语言:javascript
复制
>>>def BS(list,key,min,max):
    if max<min:
        return None
    else:
        mid=(min+(max-min)/2)
    if list[mid]>key:
        return BS(list,keyey,min,mid-1)
    elif list[mid]<key:
        return BS(list,key,mid+1,max)
    else:
        return mid

>>> min = 0
>>> list = [2, 4, 7, 13, 21, 22, 27, 31, 41, 77, 97, 144, 168]
>>> max = len(list)-1
>>> key = 21
>>> BS(list,key,min,max)

wiki说:二进制搜索或半间隔搜索算法在按键值排序的数组中找到指定输入值(搜索“键”)的位置。1在每一步中,该算法将搜索键值与数组中间元素的键值进行比较。如果键匹配,则已找到匹配的元素,并返回其索引或位置。否则,如果搜索关键字小于中间元素的关键字,则算法在中间元素左侧的子数组上重复其操作,或者,如果搜索关键字较大,则在右侧的子数组上重复其操作。如果要搜索的剩余数组为空,则在数组中找不到键,并返回一个特殊的“未找到”指示。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17951014

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档