Simple loop analysis - example 1

  • What is the running time of the following program fragment:

       for ( int i = 0; i < 10; i++ )
           doPrimitive();
    

    Analysis:

     The loop is executed 10 times for any input size
    
     Running time = 10 doPrimitive() operations
    
     Run time complexity = O(1)    (constant time)
    
    
    
    
    
    
    
    

Simple loop analysis - example 2

  • What is the running time of the following program fragment:

       n = input size (e.g.: # elements in an array)
    
       for ( int i = 0; i < n; i++ )
           doPrimitive();
    

    Analysis:

     The loop is executed n times for input size n
    
     Running time = n doPrimitive() operations
    
     Run time complexity = O(n)   (linear)
    
    
    
    
    
    

Note:   n or N will always denote the input size in algorithm analysis

Simple loop analysis - example 3

  • What is the running time of the following program fragment:

       int sum = 0;
    
       for ( int i = 0; i < 5*n; i = i + 4 )
           sum = sum + 1;
    

    Analysis:

     The loop is executed (5/4)n times for input size n
    
     Running time = (5/4)n primitive operations
    
     Run time complexity = O(n)   (linear)
    
    
    
    
    
    

DEMO: demo/13-analysis/Demo.java

Simple loop analysis - example 4

  • What is the running time of the following program fragment:

       int sum = 0;
    
       for ( int i = n; i > 0; i = i - 4 )
           sum = sum + 1;
    

    Analysis:

     The loop is executed (1/4)n times for input size n
    
     Running time = (1/4)n primitive operations
    
     Run time complexity = O(n)   (linear)