在渐近分析的情况下,迭代和递归二分搜索算法有什么区别

发布于 2024-12-09 22:06:15 字数 567 浏览 4 评论 0原文

我需要展示迭代和递归二分搜索算法的“渐近运行时分析”之间的差异。据我所知,它们具有相同的最坏情况复杂度(O(log(n)),但在某些资源中它说递归具有O(log(n)+1)。我有点困惑,有人可以帮助我关于这种情况?

使其运行时间与下面编写的代码相同。

我还需要改进 python 递归二分搜索算法,

def binarySearch(alist,item):
    if len(alist) == 0:
        return False
    else:
        midpoint = len(alist)/2
        if alist[midpoint] == item:
            return True
        else:
            if item<alist[midpoint]:
                return binarySearch(alist[:midpoint],item)
            else:
                return binarySearch(alist[midpoint+1:],item)

I need to show the differences between the iterative and the recursive binary search algorithms' asymptotic runtime analysis'. as far as i know, they have the same worst case complexity (O(log(n)) but in some resources it says that recursive has O(log(n)+1). I am a bit confused, can somebody help me about this situation?

I also need to improve a python recursive binary search algorithm to run in just as equal time as the iterative one. the code is written below.

thanks!

def binarySearch(alist,item):
    if len(alist) == 0:
        return False
    else:
        midpoint = len(alist)/2
        if alist[midpoint] == item:
            return True
        else:
            if item<alist[midpoint]:
                return binarySearch(alist[:midpoint],item)
            else:
                return binarySearch(alist[midpoint+1:],item)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风启觞 2024-12-16 22:06:15

O(log(n) + 1) 与 O(log(n)) 相同——渐近地,它们产生相同的函数集。常数加法被忽略,就像常数倍数一样。

它们在空间使用方面有所不同——递归二分搜索将使用 log(n) 空间(因为堆栈),除非尾部调用被编译器删除并转换为非递归定义。

无论如何,您的算法在性能上会显着下降,因为切片非常昂贵(O(n))。

O(log(n) + 1) is the same as O(log(n)) -- asymptotically, they produce the same set of functions. The constant addition is ignored, just like constant multiples.

They are different in terms of usage of space -- recursive binary search will use log(n) space (because of the stack) unless the tail-calls are removed by the compiler and turned into a non-recursive definition.

Anyway, your algorithm loses out significantly in performance because slicing is very expensive (O(n)).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文