[英]Big O notation and Recursion
I am having some trouble working out the Big O notation for these 2 recursive functions: 我在为这两个递归函数制定Big O表示法时遇到了一些麻烦:
int calc (int n)
{
if (n <= 0)
return 0 ;
else if (n > 10)
return n ;
else
return calc (5 + calc(5n));
}
In the case above I think the Big O notation might be O(n^2) because of the nested iterations in the data set? 在上面的例子中,我认为Big O表示法可能是O(n ^ 2),因为数据集中的嵌套迭代?
boolean method (int k ,int [] arr, int i, int j)
{
if (i > j)
return false;
if (arr [(i+j)/2] == k)
return true;
if (arr [(i+j)/2] < k)
return method (k, arr, i, ( (i+j)/2) - 1) ;
else
return method (k, arr, ((i+j)/2)+1, j) ;
}
Here I think the big O notation might be O(log N) because the input data set is halved with each iteration? 在这里,我认为大O符号可能是O(log N),因为每次迭代输入数据集都减半了?
I am, however, very new to Big O notation and any help or explanations would be much appreciated! 但是,我对Big O表示法很新,任何帮助或解释都会非常感激!
For calc
: 对于calc
:
This function will never be called more than 5 times during recursion. 在递归期间,此函数永远不会被调用超过5次。 It's easy to see from a brief analysis and substituting a few values for n
. 从简短的分析中可以很容易地看出并用一些值代替n
。 Thus it's O(1)
. 因此它是O(1)
。 Hint: the function will get called more times the smaller n
is (above some threshold). 提示:当较小的n
(超过某个阈值)时,函数将被调用更多次。
Maybe a bit of a bold statement, but I believe any function (assuming n
is the input / input size) with if (n > max) return const;
也许有点大胆的陈述,但我相信if (n > max) return const;
任何函数(假设n
是输入/输入大小) if (n > max) return const;
has to be O(1)
(just let the "constant" be the maximum time taken for n <= max
). 必须是O(1)
(只要让“常数”为n <= max
)所需的最大时间。
For method
: method
:
Yes, it's O(log n)
. 是的,它是O(log n)
。
The function is actually binary search, which is a good thing to know. 该函数实际上是二进制搜索,这是一件好事。
Dukeling is correct. Dukeling是对的。 The first is O(1) and the second is O(log N) 第一个是O(1),第二个是O(log N)
But given the title of this question I think it is important to remember that recursion is not special. 但考虑到这个问题的标题,我认为重要的是要记住递归并不特殊。 Any recursive function can be re-written as a loop there is no difference when looking at them versus a standard loop. 任何递归函数都可以重写为循环,在查看它们与标准循环时没有区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.