Data structures and algorithms help!

hayood

New member
Joined
Feb 16, 2010
Messages
37
Perform a worst-case analysis of each of the following fragments and give a ? bound for the running time:
a. sum = 0;
for (int i = 0; i < N; i++)
for (int j = i; j ? 0; j--)
sum++;

My confusion here is how do i count the number of iterations in a for loop and the running time.
what i did:

i calculated the Running time of each line
1) sum = 0 is O(1)
2) For... O(N)
3) ?
4) O(1)

I am guessing i should add them up and try to get the running time but I need someone to explain to me how to solve such problem please.
 
The time is for the for-loops may be calculated as:

i=0, j=0: count =1
i=1, j=1 + i=1, j=0: count = 2
... etc
i=N-1,j=N-1 + i=N, j=N-1 + ... + i=N, j=0: count=N

Adding up each line will yield 1+2+3+...+N. From calculus, you know a formula for this (right?), giving time O(N^2)
 
Top