【问题标题】:Which way is better for Binary Search? [closed]哪种方式更适合二分搜索? [关闭]
【发布时间】:2022-01-02 03:37:41
【问题描述】:

我曾尝试自己在 python 中实现一个二进制搜索算法并且它有效,但是当我查看互联网时,他们中的大多数人都做了不同的事情。我不知道这两个哪个更好

我的二分搜索算法

def binary_search(arr, item):

    minVal = 0
    maxVal = len(arr) - 1
    backtrack = 0

    while (True):
        midPosition = (maxVal - minVal)//2 + backtrack
        mid = arr[midPosition]

        if mid > item:
            maxVal = midPosition
            backtrack = midPosition
        elif mid < item:
            minVal = midPosition
            backtrack = midPosition
        else:
            print(midPosition)
            break

教程的二分查找算法

def binary_search(arr, x):
    low = 0
    high = len(arr) - 1
    mid = 0
 
    while low <= high:
 
        mid = (high + low) // 2
 
        # If x is greater, ignore left half
        if arr[mid] < x:
            low = mid + 1
 
        # If x is smaller, ignore right half
        elif arr[mid] > x:
            high = mid - 1
 
        # means x is present at mid
        else:
            return mid
 
    # If we reach here, then the element was not present
    return -1

【问题讨论】:

  • 明确您所说的“更好”的含义可能有助于其他人回答您的问题。在性能方面更好?还是可读性?还是其他一些绩效衡量标准?
  • (您的xyzVals 是索引,而不是值。然后是Style Guide for Python Code。)
  • 你是如何测试提供的代码的?

标签: python algorithm binary-search choice


【解决方案1】:

你的算法不正确。

例如,这个调用会导致一个无限循环:

binary_search([1,2,3], 3)

而且,您的代码没有规定搜索的值何时不在列表中,并且循环将永远继续。

出现这些问题的原因:

首先,backtrack 值应始终为minVal。因此,您将不再受益于这个额外的变量。

其次,当您缩小搜索“窗口”的范围时,您应该从该新窗口中排除 mid 索引。

最后,这样的函数不应该打印结果,而是返回结果。这对于使您的函数可重用至关重要,因为它允许调用者将结果存储在变量中而不是打印它。

修正

为了使您的代码正常工作,它应该如下所示:

def binary_search(arr, item):
    minVal = 0
    maxVal = len(arr) - 1

    while minVal <= maxVal:  # stop when window is empty
        # must always add minVal
        midPosition = (maxVal - minVal)//2 + minVal
        mid = arr[midPosition]
        if mid > item:
            # exclude midPosition from new window
            maxVal = midPosition - 1
        elif mid < item:
            # exclude midPosition from new window
            minVal = midPosition + 1
        else:
            return midPosition  # don't print
    return -1  # not found

现在您的功能与您在其他地方找到的功能几乎相同。以下公式在数学上是等价的:

    (maxVal - minVal)//2 + minVal
    (maxVal + minVal)//2

在 Python 中,没有理由选择更长的。

【讨论】:

  • 优秀的分析和解释!我希望OP会采取相应的行动。
【解决方案2】:

虽然两种算法基本相同(它们需要相同数量的迭代),但第一种算法会慢一些,因为您有一个额外的分配。第二个代码中的加法/减法很可能总是更便宜。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-10
    • 2016-06-10
    • 1970-01-01
    • 2015-05-26
    • 2014-10-27
    • 2014-07-30
    • 1970-01-01
    • 2013-06-20
    相关资源
    最近更新 更多