在渐近分析的情况下,迭代和递归二分搜索算法有什么区别
我需要展示迭代和递归二分搜索算法的“渐近运行时分析”之间的差异。据我所知,它们具有相同的最坏情况复杂度(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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)).