Big O for nested series for loops

I have a question about calculating Big O runtime for a series of loops that are nested in an outer for loop.

For instance:


for (50,000 times)
{
    for (n times)
    {
        //Do something
    }
    for (n-2 times)
    {
        //Do something
    }
    for (n times)
    {
        //Do something
    }
    for (n-2 times)
    {
        //Do something
    }
}

The outer loop is constant, so I think this is ignored. Is it really so easy to make the following calculation?

N + N-2 + N + N-2

2N + 2 (N-2)

4N - 4

O (4N - 4)

O (4N) - after removing the constant -4

Is it correct?

Thank.

+5
source share
3 answers

This is O (n)

(you are only interested in the "largest" part of the equation, and you divide the constant).

If you had a loop i from 1..n and another loop inside j from i..n, that would be O (n ^ 2).

+6
source

. , O(N). , 4O(N), 50, 000, , N.

0

This is O (N). But in this context, depending on what you have for N, a constant can greatly affect the performance of your algorithm.

0
source

All Articles