Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Theta time complexity of a recursive function

Finding the Theta order runtime of the following snippet of code is giving me trouble:

void foo(int n)
{
    if (n <= 1)
    {
        return;
    }

    for(i = 0; i < n; i++)
    {
        cout << endl;
    }

    foo(n / 2);
    foo(n / 2);
}

The if statement is Θ(1). The for loop is Θ(n). It seems to me that the recursive function calls are Θ(log n). My understanding is that I would add up the Thetas, and the highest order (Θ(n)) would survive, and the segment of code is order Θ(n). Is my understanding correct?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No. Consider:

  1. Go through N values
  2. Repeat for N/2 values
  3. Repeat for N/2 values

We can rewrite that as:

  1. Go through N values
  2. Repeat for N values

If it were not recursive that’d just be 2N → Θ(n)…

but since it is recursive you repeat things N times, so it is:

Θ(n²)

BTW, it is Big-Θ since the upper bound (Big-O) and lower bound (Big-Ω) are the same.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading