Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of growth for loops

What would be the order of growth of the code below. My guess was, each loop's growth is linear but the if statement is confusing me. How do I include that with the whole thing. I would very much appreciate an explanatory answer so I can understand the process involved.

int count = 0;
for (int i = 0; i < N; i++)
for (int j = i+1; j < N; j++)
for (int k = j+1; k < N; k++)
if(a[i] + a[j] + a[k] == 0)
count++;
like image 830
JVTura Avatar asked Apr 16 '15 17:04

JVTura


2 Answers

There are two things that can be confusing when trying to determine the code's complexity.

  1. The fact that not all loops start from 0. The second loop starts from i + 1 and the third from j + 1. Does this affect the complexity? It does not. Let's consider only the first two loops. For i = 0, the second runs N - 1 times, for i = 1 it runs N - 2 times, ..., for i = N - 1 it runs 0 times. Add all these up:

    0 + 1 + ... + N - 1 = N(N - 1) / 2 = O(N^2).
    

    So not starting from 0 does not affect the complexity (remember that big-oh ignores lower-order terms and constants). Therefore, even under this setting, the entire thing is O(N^3).

  2. The if statement. The if statement is clearly irrelevant here, because it's only part of the last loop and contains no break statement or other code that would affect the loops. It only affects the incrementation of a count, not the execution of any of the loops, so we can safely ignore it. Even if the count isn't incremented (an O(1) operation), the if condition is checked (also an O(1) operation), so the same rough number of operations is performed with and without the if.

    Therefore, even with the if statement, the algorithm is still O(N^3).

like image 104
IVlad Avatar answered Dec 07 '22 06:12

IVlad


Order of growth of the code would be O(N^3).

In general k nested loops of length N contribute growth of O(N^k).

like image 45
Neithrik Avatar answered Dec 07 '22 05:12

Neithrik