【问题标题】:Binary Search in Python 2 variable not updating causing an infinite loop.....why is the variable not updating?Python 2 变量中的二进制搜索未更新导致无限循环.....为什么变量未更新?
【发布时间】:2013-09-17 12:14:40
【问题描述】:

这是我的二分搜索。 mid不更新,无限循环。

def binary_search (z, A, start, end):
    if len(A) == 0:
        return None
    else:
        mid = start + (end - start) / 2
        if (z < A[mid]) and (z > A[mid-1]):
            return A[mid-1]
        elif (z < A[mid]):
            return binary_search(z, A, start, mid)
        elif (z > A[mid]):
            return binary_search(z, A, mid, end)

【问题讨论】:

    标签: python search binary


    【解决方案1】:
    def binary_search (z, A, start, end):
        if end < start:
            return None
        else:
            mid = start + (end - start) / 2
            if (z < A[mid]):
                return binary_search(z, A, start, mid-1)
            elif (z > A[mid]):
                return binary_search(z, A, mid+1, end)
            else: 
                return mid
    

    我改变了一些东西。

    我首先检查更改了end &lt; start:,因为if len(A) == 0: 将保持不变并且不允许您将其用作基本情况。

    此外,当您返回二进制搜索时,您需要跳过中间值,因为那是您要返回的值。

    我测试了代码,它工作正常!

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      • 2023-03-04
      • 2021-06-29
      相关资源
      最近更新 更多