问题
Can someone please help me with the run-time analysis of the following code:
public static void f(int n)
{
for (int i = 0; i <= n; i++)
{
System.out.print("+" + i);
}
if (n <= 1)
{
return;
} else
{
f(n / 3);
f(n / 3);
}
}
According to me, the run-time for the recursive formula for the code is:
T(n) = cn + 2T(n/3)
And I think the answer should be Θ(nlog(n))
, but the book solutions show it to be Θ(n)
.
Also the book says to assume n = 3^k
for simplicity.
Can someone please explain the correct answer to me?
回答1:
Consider using the Master Theorem. Your situation corresponds to Case 1, where f(n)=cn is O(n). with a=2 and b=3, and applying the theorem, we have that T(n) is bigTheta(n^log3(2)), which is BigTheta(n).
Hope it helps ...
来源:https://stackoverflow.com/questions/16001335/runtime-analysis-of-the-following-recursive-method