简体   繁体   中英

How do I find the time complexity (Big O) of this block of code?

I am trying to understand how this O notation works and I have below here a block of code, and next to each LINE I will have a comment with the time complexity that I believe it to be. If I am wrong please correct me and explain why my logic is not correct.

Code #1

for (int i = 0; i < n; i++) <<<<<<<<<<<<<<<<<<< O(1)*O(N)
 {
    for (int j = 0; j < 3; j++) <<<<<<<<<<<<<<< O(1)*O(1)
      {
        for (int k = 0; k < 3; k++) <<<<<<<<<<<<<<O(1)*O(1)
          {
            printf("%d", arr[i]); <<<<<<<<<<<<<<O(1)
           }
        printf("\n"); <<<<<<<<<<<<<<<<<<O(1)
    }

}

Running time = O(N), after adding everything up.

Code #2

for (int i = 2; i <= n; i++) <<<<<<<<<<<<O(1)*O(N)
{
        int j;<<<<<<<<<<<<<<<<<<<<<<<O(1)
        printf("\n%d:", i);<<<<<<<<<<<<<<O(1)
        for(j = 2; j <= i; j = j * 2) <<<<<<<<<<<O(n-2)??????????
        {
            printf("%d ", j);<<<<<<<<<<<<<<O(1)
        }
         printf("\n%d:", i);<<<<<<<<<<<<<<<<<<<<O(1)
         for(int k = j/2; k >= 2; k = k / 2)<<<<<<<<<<<<<I am not sure of this one
        {
             printf("%d ", k);
        }
  }

Running time: Unsure..

Overall, I KINDA get the idea of it, but still not fully sure of how to use it in some situations. Does anyone else also have a guide or some sort that gives examples and explanations of the time complexity of for loops and while loops?

the block of k is O(lg j) , where j is O(n) , so k is O(lg n) . but if you considering to whole program, it's O(n lg n) .

Here's the rules:

  • Loop is number of iterations times complexity of the body
  • Consecutive blocks are sum of complexities
    • But in O() only the asymptotically largest term is relevant, so you can immediately simplify to the higher complexity
  • Multiplicative constants are irrelevant
  • Geometric progression (the j loop with j = j * 2 and the k loop with k = k / 2 ) has complexity O(log n)

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