views:

453

answers:

3
sum(array,n)
{
  tsum=0;
  for(i=0;i<n;i++)
    tsum=tsum+array[i];
  return tsum;
}
+2  A: 

In terms big-O, that's linear in proportion to the number of array elements processed, so O(n)

(Note, your code overwrites the i parameter, presume that parameter was intended to be n, to indicate the number of array elements to sum?)

Paul Dixon
+1  A: 

You declare tsum=0 in 1 step, then you run the loop for n steps. in each iteration, you do a sum which is 1 step, and then you return tsum in 1 step. Your step count is approximately:

1 + 3n + 1, which is O(n) in terms of the big-oh notation, which ignores constants, and all lower order terms (if there are a constant number of them.) There are 3n steps as in each iteration, you increment the variable i, check if it is less than n, and then enter the loop to do the computation.

+1  A: 
                                Cost         Times
tsum=0;                         c1             1
for(i=0;i<n;i++)                c2             n+1
    tsum=tsum+array[i];         c3             n
return tsum;                    c4             1

The total cost of algorithm is 1*c1 + (n+1)c2 + nc3 + 1*c4

Thus, the time required for this algorithm is proportional to n.

Can