简体   繁体   English

哪种方式更适合二分搜索?

[英]Which way is better for Binary Search?

I have tried to implement a binary search algorithm by myself in python and it worked but when I looked into the internet most of them did differently.我曾尝试在 python 中自己实现一个二进制搜索算法并且它有效,但是当我查看互联网时,他们中的大多数人都做了不同的事情。 I don't know which one is better from these two我不知道这两个哪个更好

My Binary Search Algorithm我的二分搜索算法

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

Tutorial's binary search algorithm教程的二分查找算法

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

While both algorithms are basically the same (they need the same amount of iterations), the first one is a little bit slower since you have an additional assignment.虽然这两种算法基本相同(它们需要相同数量的迭代),但第一个算法要慢一些,因为你有一个额外的分配。 The addition/subtraction in the second code is most likely always cheaper.第二个代码中的加法/减法很可能总是更便宜。

Your algorithm is not correct.你的算法不正确。

For instance, this call will lead to an infinite loop:例如,此调用将导致无限循环:

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

But also, your code has no provision for when the searched value is not in the list, and also then the loop will continue forever.而且,当搜索的值不在列表中时,您的代码没有任何规定,并且循环将永远继续。

Reasons for these issues:这些问题的原因:

First of all, the backtrack value should always be minVal .首先, backtrack值应始终为minVal And for that reason you would no longer benefit from this extra variable.因此,您将不再受益于这个额外的变量。

Secondly, when you narrow down the search "window", you should exclude the mid index from that new window.其次,当您缩小搜索“窗口”的范围时,您应该从新的 window 中排除mid索引。

Finally, such a function should not print the result, but return it.最后,这样的 function 不应该打印结果,而是返回它。 That is essential for making your function reusable , as it allows the caller to store the result in a variable instead of printing it.这对于使您的 function可重用至关重要,因为它允许调用者将结果存储在变量中而不是打印它。

Correction更正

In order to make your code work, it should look like this:为了使您的代码正常工作,它应该如下所示:

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

And now your function is almost the same as the one you found elsewhere.现在您的 function 与您在其他地方找到的几乎相同。 The following formulas are mathematically equivalent:以下公式在数学上是等价的:

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

In Python there is no reason to choose the longer one.在 Python 中没有理由选择更长的那个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM