views:

2255

answers:

5

What is the Big-O time complexity of the following nested loops:

for(int i = 0; i < N; i ++) 
{
    for(int j = i + 1; j < N; j++)
    {
        System.out.println("i = " + i + " j = " + j);
    }

}

Would it be O(n^2) still?

+9  A: 

Yep, it's still O(n^2), it has a smaller constant factor, but that doens't affect O notation.

Alex Gaynor
+3  A: 

Yes, it would be N squared. The actual number of steps would the sum of 1 to N, which is .5*(N - 1)^2, if I'm not mistaken. Big O only takes into account the highest exponant and no constants, and thus, this is still N squared.

Charles Graham
You're off by just a bit - the sum from 1 to n is n*(n+1)/2, or .5*n^2+.5*n, which is clearly O(n^2).
+3  A: 
Charlie Martin
+5  A: 

It's N squared if you ignore the System.out.println. If you assume that the time taken by that will be linear in its output (which it may well not be, of course), I suspect you end up with O ( (N^2) * log N).

I mention this not to be picky, but just to point out that you don't just need to take the obvious loops into account when working out complexity - you need to look at the complexity of what you call as well.

Jon Skeet
You say it implicitly, but it should be noted explicitly that complexity depends on what you consider "unit of work". If println is unit of work, then it's O(n^2), if machine instruction is unit of work, then it's as you say.
It's pretty odd for the unit of work to depend on n though - or at least, it makes it less useful in the real world, IMO.
Jon Skeet
A: 

yup,,,,,in worst case analysis its surely N square.

sohaib shah