Program Algorithmic time

29 Views Asked by At

Just a simple question to get the total time to do a particular program or calculate Big O of the function

Lets say I have an n x n array

x = 0, y = 0

for i = z to n:

x = i + 1

y = i - 1

C[i][i] = C[x][y]

next i

Ignoring the actual way the program run, just thought of it on the fly. My question is for the cost of time to run this, is it just (n-z+1)*2

2 from (addition and subtraction)

(n-z+1) for number of instance/iterations of the for loop

do you count also the array substitution as well, hence its (n-z+1)*3?

1

There are 1 best solutions below

3
On BEST ANSWER
for i= 1 to n -> 1 for
  x= i-1 -> 1 -, 1 =
  y= i+1 -> 1 +, 1 =
  c[i][i]= c[x][y] -> 2 [][], 1 =
endfor

I have tried to annotate the code with "costs". for denotes the cost of one loop iteration (increment and exit test); = denotes a variable assignment; [][] denotes indexing of a 2D array.

The loop is executed exactly n times, and the accounting gives

n for, n +, n -, 3n =, 2n [][]

It actually makes no sense to add up these terms and conclude 8n operations as we don't know if the costs are equal. In reality, they are not, they are not even constant, they are highly architecture-dependent, and we can't even know them precisely.

All we can reasonably say is that the running time will be approximately proportional to n.