user1174727
user1174727

Reputation:

Time complexity function of a nested loop given the following loop

for(i = 1; i <= n; i++)
{
    j = n;
    while(j >= 1)
    {
        // . . . body of the loop needs Θ(1)
        j = j / 2;
    }
}

Upvotes: 0

Views: 2840

Answers (1)

ose
ose

Reputation: 4075

I am assuming in this question that n has already been set outside the loop; and by your code will remain constant during execution.

Your question is a bit unclear but my understanding is that you want to know the time complexity of the entire code.

Let's take a look at the outer loop. Notice that i++ increments the loop by 1 each time and the loop goes up to n. Because the loop increments by 1, it is said to be O(n) as the number of iterations grows linearly with the value of n.

Next, examine the inner loop. You can see by the lines j = n and while(j >= 1) that the loop begins at n and goes down to 1. Suppose that inside the while loop you had the code j--. This would mean that the number of iterations of the inner loop would increase linearly with n, just as in the outer loop.

However, the body of the loop is j = j / 2 (assume integer division here, also assuming by your comment that the rest of the body of the loop is O(1) - ie it is inconsequential). Let's have a quick look at some sample values of n for the inner loop:

n         # iterations of while loop

1         1

2         2

3         2

4         3

5         3

6         3

7         3

8         4

9         4

10         4

11         4

12         4

13         4

14         4

15         4

....

You can probably see the pattern emerging - one 1, two 2s, four 3s, eight 4s. These are powers of 2. So given the value of n we can determine the number of iterations:

iterations = FLOOR(Log base 2(n)) + 1.

We need to use FLOOR to simulate the integer division, and the + 1 takes care of the fact that we loop while j is greater than or equal to 1.

So the number of iterations grows by Log base 2 of n. The 1 is not relevant here because we are interested in big-O notation where constant multiples or additions have no effect on the growth of one function relative to the growth of another function.

So to summarize so far: the outer loop is growing at rate O(n) while the inner loop is growing at O(Log base 2 n) (which is normally written as just Log(n)).

Now, when dealing with nested loops, the complexity of the total code is found by multiplying the complexities of the nested loops. This is because for every iteration of the outer loop, we must complete Log(n) inner loops. (See this question for more info).

So now you can see that the total complexity of the snippet you have provided is n * Log(n).

If you want to read more about big-O, see here.

Upvotes: 2

Related Questions