简体   繁体   中英

Time complexity of this nested for loop

for (int i = 0; i < this.tiles.length * this.tiles.length; i++) {
        int row = i / this.tiles.length;
        int col = i % this.tiles.length;
        for (int j = i+1; j < this.tiles.length * this.tiles.length; j++) {
            int compareRow = j / this.tiles.length;
            int compareCol = j % this.tiles.length;
            if(this.tiles[compareRow][compareCol] < this.tiles[row][col]) {
                count++;
            }
        }
    }

I have to calculate the time complexity of this function, i first thought it was ~n*n-1 but i'm pretty sure that's actually wrong. Can anybody explain what the time complexity of this piece of code is?

There are 2 for loops each iterating (tiles.length*tiles.length) times. So it is:

Number of times of comparison:

  • First set of comparison(i=0): tiles.length 2

  • Second set of comparison (i=1): tiles.length 2 -1

  • .

  • .

  • Last set of comparision(i=tiles.length 2 -1 ): 1

= ( ( tiles.length 2 ) + ( tiles.length 2 -1 ) + ( tiles.length 2 - 2)....... + 2 + 1 )

= O(tiles.length 3 )

 for (int i = 0; i < this.tiles.length * this.tiles.length; i++) { //O(n)
        int row = i / this.tiles.length; 
        int col = i % this.tiles.length; 
        for (int j = i+1; j < this.tiles.length * this.tiles.length; j++) { //O(n^2) it's squared because there are two loops
            int compareRow = j / this.tiles.length; //n +
            int compareCol = j % this.tiles.length; //+ n
            if(this.tiles[compareRow][compareCol] < this.tiles[row][col]) {  //n
                count++; 
            }
        }
    }

O(n^2 + n) == O(n^2)

The way I was taught was that for every loop it's O(n) so, a nested loop would naturally be O(n^2), and with every condition or operation would be n + n..nth which is where O(n^2 + n) = O(n^2)

Hope that helped a bit.

checkout the resource below for a more depth explanation.

Resources:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM