reset password
Author Message
jpascua
Posts: 197
Posted 16:41 Oct 03, 2014 |

Can someone please provide more examples on how to find the running time of a pseudocode?

yxu22
Posts: 25
Posted 17:45 Oct 03, 2014 |

Generally, we need to check several cases:

1. If this line is a simple statement, which means a statement except functions or loops ( for loop or while loop or other loop), we calculate the running of time of this line as constant (we use O(1) to indicate constant running time)

eg. a = a+1

eg. if b > 0

2. If this block is a loop, we calculate the running time of the loop as how many iterations the loop runs.

eg. for i <- 1 to 10      // the for will iterate like i=1, i=2, i=3,...,i=10, so this for loop will iterate 10 times

eg. for i <- 1 to n       //  this for loop will iterate n times, so the running time of this loop is O(n)

eg. i = 10;

while (i > 1 ){

i = i / 3

}        // this while loop will iterate 3 times

3. If this block contains nested loop(s),

eg.

for i <- 1 to n {

      for j <- 1 to n {}

}  

//  second for loop will iterate n times, first for loop will iterate n * n which is n^2 times, so running time is O(n^2)

However, if loops are not nested with each other,

eg. 

for i <- 1 to n {}

for j <- 1 to n {}

// running time is n + n which is 2n , O(n)

4. If a statement is a function call, we need calculate running time of that function. 

If a statement is a recursive function call, it is better to use some methods such as recursion tree method to figure out how many times we call that function.

eg. Merge-Sort

 

Sometimes mathematical summary formulas will be helpful for some hard questions.

After we know each line or each block 's running time, we pick the highest order terms.

Last edited by yxu22 at 17:47 Oct 03, 2014.
jpascua
Posts: 197
Posted 21:54 Oct 04, 2014 |

What do you mean by highest order terms?

Last edited by jpascua at 22:00 Oct 04, 2014.