runtime analysis of the following recursive method

耗尽温柔 提交于 2019-12-12 01:35:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!