这个递归算法的运行时间是多少?

时间:2014-04-06 22:25:53

标签: big-o complexity-theory time-complexity binary-search-tree

Search_item(A,item,c)

index <- c   

If (A[index] > item)
Then 
      index <- 2 * index
      Search_item(A, item, index)
Else
If (A[index] < item)
Then 
      index <- 2 * index + 1
      Search_item(A, item, index)
Else

Return index

1 个答案:

答案 0 :(得分:0)

你提供的信息很少(没有)。这是非常难过的,但我会给出答案,希望你在其他问题上表现出更多的努力,因为我会努力回答你的问题。

您发布的算法似乎不完整。我认为有一些Return缺失了。但是:

最简单的复杂性分析是这样的:
您处理数组A。设nA中的元素数。在每次递归调用中,您要么将当前索引乘以2(并进行另一次递归调用),要么返回当前索引。
假设您的算法正确,您只能使用k进行2k < n次递归调用。所以k < log₂(n)成立。

这意味着您的算法的时间复杂度为O(log n)

由于您的算法被命名为&#34;搜索&#34;算法,看起来数组A是二叉搜索树的表示,您的搜索算法是递归二进制搜索。
这符合我计算的复杂性。