3

In this example, I have two separate for loops. Is the running time O(num1 + num2)?

for(int i=0; i< num1 ; i++)     
{
   print i;
}

for(int i=0 ; i<num2 ; i++)
{
    print i;
}

And for this example, there is a nested for loop. Would the running time be O(num1*num2) because for each number in 0 to num1, you have to iterate from 0 to num2?

 for(int i=0 ; i<num1 ; i++)
 {
     for(int j=0 ; j<num2 ; j++)
     {  
         print i;
     }
}
sg7
  • 6,108
  • 2
  • 32
  • 40
Yi Son
  • 235
  • 1
  • 4
  • 9
  • 2
    Instead of worrying about big O right away, why don't you first calculate how many numbers will be printed by each of those snippets for a couple of values for `num1, num2`? That should give you some intuition. –  Mar 28 '13 at 02:57
  • The first example is O(n) and the second is O(n^2). Big-O notation indicates how the run time increases with the size of the input, you don't put the actual numbers in. – Blorgbeard Mar 28 '13 at 02:59
  • First Case is Num1+Num2 Big-O =O(n) and Second Case Num1*Num2 Big-O = O(N^2) – aked Mar 28 '13 at 03:24
  • You should realize that the index variable in the second example shouldn't be `i` in both loops.. – Mike Dinescu Mar 28 '13 at 12:32

1 Answers1

4

You can be more general. Big-O notation isn't about finding exact values given your actual parameters. It is about determining asymptotic runtime. In this case, we can just replace num1 and num2 with n, where n is the upper bound of some interval starting at 0. Using this method, we would find the runtime of your first example to be O(n), and the second example would have a runtime O(n^2). The first example runs in linear time, and the second example is quadratic. You rarely need to go into more detail than this to categorize algorithmic runtime.

kronion
  • 711
  • 4
  • 14
  • 1
    So, if `for(int i=0; i< num1 ; i++) { print i; }` is **O(n)** then why are two iterations still **O(n)**? Wouldn't it be **O(n*2)** since you are iterating twice instead of just once? – user1477388 Apr 21 '16 at 18:38
  • 2
    While you are correct about the coefficient, Big-O notation does not include that level of detail. It only conveys the order of magnitude of runtime. See http://stackoverflow.com/questions/2081846/big-o-notation-question – kronion Apr 21 '16 at 19:03