简体   繁体   中英

Why is the given algorithm O(n^2)?

I'm looking at an algorithm and trying to break it down and come up with the Big O notation for it. However, I am unable to deduce why it is O(n^2)

I can see that the outer loop goes to N, but the inner loop is throwing me off

int a = 0;
for (i = 0; i < N; i++) {
    for (j = N; j > i; j--) {
        a = a + i + j;
    }
}

Does anyone know how I can best approach these kinds of questions, if they were to pop up in an interview? I want to get better at analyzing algorithms

The outer loop iterates from 0 to N-1 .

The inner loop iterates from N down to i+1 .

That means in the first iteration of the outer loop, the inner loop takes N steps. In the second iteration of the outer loop, the inner loop takes N-1 steps. In the third iteration of the outer loop, the inner loop takes N-2 steps. ... This continues until the last iteration of the outer loop, where the inner loop takes 1 step.

The total number of steps is therefore N + (N-1) + (N-2) + ... + 2 + 1 , or (rearranged) 1 + 2 + ... + (N-1) + N . This sum is equal to N * (N+1) / 2 ( see here for details), which expands to 0.5 * N^2 + 0.5 * N . Ignoring lower powers and constant factors means this is in O(N^2).

If you're a visual person, you can think of the outer loop as rows, and the inner loop as columns. For each iteration of the outer loop, the number of iterations (columns) in the inner loop decreases by 1.

Presenting this visually, you get:

* * * * * 
  * * * * 
    * * * 
      * * 
        * 

This is half a square (triangle), so approximately (n^2)/2, which is O(n^2).

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