Search code examples
algorithmpseudocode

Pseudo Code Algorithm: finding number of iterations + best/worst case scenarios


Given the following pseudo code, I am supposed to find out how many times the statement in the innermost loop is executed, as a function of n, and what the best and worst case scenarios of order of operations of this algorithm is.

Algorithm What(A,n)
  A <-- new 2D array of n*n integers
  s <-- 0
  for I <-- 2 to n-2 do
     for j <-- I-2 to n-1 do
        s <--s + A[I][j]
     end for
   end for

I am just having trouble with conceptualizing how to figure this stuff out. Any help would be greatly appreciated :)


Solution

  • Algorithm What(A,n)
      A <-- new 2D array of n*n integers
      s <-- 0
      for I <-- 2 to n-2 do        
         for j <-- I-2 to n-1 do   ---> this executes (n-1)-(I-2)+1 times=n-I+2 times
            s <--s + A[I][j]
         end for
       end for
    

    Analysis

    So T(n)= sum over I ( n-I+2) = 0+1+2+...+n times [ for I= n-2 down to 2] = n(n+1)/2

    T(n)= O(n^2)

    Reference: Study Cormen's Book Introduction to algorithms or Algorithms Unlocked (if you are a beginner). You will get accustomed with the analysis procedure.