Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big O for 2D for loop

I have to write down the Big O notation of an algorithm I had to think up for my homework.

I'm able to tell that the code below is O(n^2). Because for every x I have to go through all of the y's and it becomes slower as the world grows larger.

int[][] world = new world[20][20];
for (int x = 0; x < 20; x++)
{
    for (int y = 0; y < 20; y++)
    {
        ..
    }
}

But, for another question I have to go through the bottom half of the world, so my y loop gets halved.

int[][] world = new world[20][20];
for (int x = 0; x < 20; x++)
{
    for (int y = 10; y < 20; y++)
    {
        ..
    }
}

I'm not quite sure what Big O notation is appropriate for the above loop, is it still O(n^2) because it still becomes slower the bigger the world gets? Or is it O(log n) because the y is halved?

like image 412
Kevin Avatar asked Nov 29 '25 06:11

Kevin


2 Answers

it is simply speaking O(n*n/2)=O(n^2) since constants arent considered in big O.

like image 84
Anurag Ramdasan Avatar answered Nov 30 '25 19:11

Anurag Ramdasan


It's O(n^2) as y is still a function of n i.e. O(n^2/2) is still O(n^2).

like image 44
P.P Avatar answered Nov 30 '25 19:11

P.P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!