![](/img/trans.png)
[英]Wrote Binary Search algorithms for Python, both a recursive and iterative version. How would you judge their efficiency?
[英]what is the difference between iterative and recursive binary search algorithms in case of asymptotic analysis
我需要展示迭代和递归二进制搜索算法'渐近运行时分析'之间的差异。 据我所知,它们具有相同的最坏情况复杂度(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)
O(log(n)+ 1)与O(log(n))相同 - 渐近地,它们产生相同的函数集。 常量加法被忽略,就像常数倍数一样。
它们在空间使用方面有所不同 - 递归二进制搜索将使用log(n)空间(因为堆栈),除非尾部调用被编译器删除并转换为非递归定义。
无论如何,你的算法在性能上显着下降,因为切片非常昂贵(O(n))。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.