【问题标题】:Recursive binary search which returns index返回索引的递归二分查找
【发布时间】:2020-04-21 07:00:09
【问题描述】:

我正在参加 CS 课程的介绍,并被分配执行递归二进制搜索,该搜索返回搜索项的索引,如果它存在于列表中,否则它应该返回负数。

对该函数进行分类的代码如下: (python代码)

numList = [1,2,3,4,5,...6,7,8,9]
key = <insert number to search for here>
position = binarySearch(numList, key)
print("Your number is at " + str(position))

我不能修改函数的参数。

给定

def binarySearch(numList, key):
   <code here>

关于如何做到这一点的任何提示?我似乎总是无法恢复原始号码的索引。二分查找必须是递归的。

【问题讨论】:

标签: python recursion binary-search


【解决方案1】:

geeksforgeeks复制二进制搜索

根据问题陈述实现代码

numList = [1,2,3,4,5,6,7,8,9]
key = 6

def binarySearch(numList, key):
    def binary_search(alist, start, end, key):
        """Search key in alist[start... end - 1]."""
        if not start < end:
            return -1

        mid = (start + end)//2
        if alist[mid] < key:
            return binary_search(alist, mid + 1, end, key)
        elif alist[mid] > key:
            return binary_search(alist, start, mid, key)
        else:
            return mid
    return binary_search(numList, 0, len(numList), key)

print(binarySearch(numList, key)) # otput 5, index start from 0

【讨论】:

  • 有没有什么方法可以在没有内部方法的情况下实现这一点?或者是正确检索索引所必需的“开始”和“结束”变量。
  • @jpgamer31 binary search 这可能会有所帮助
猜你喜欢
  • 2020-10-26
  • 1970-01-01
  • 2015-12-16
  • 1970-01-01
  • 2012-12-19
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
  • 2020-11-13
相关资源
最近更新 更多