1

Say I have a snippet of code:

k = 5
i, j = 0

for i -> n
    if i == k
        for j -> k
            /* do something */ 
        end for
    k = k * 4/3
    end if
    /* do something */
end for

I can tell that the algorithm is worse than n but can't be worse than n^2. In fact it seems like it would be less than n log (n). Though I admit these are just guesses I'm making. Is there any methodology to figuring out what the big theta is for such algorithms?

HLM
  • 111
  • 2

2 Answers2

1

In order to estimate the running time of the code it is enough to count the number of times the two "do-somethings" are executed. Call them do-something 1 and do-something 2 (in their order of appearance). Do-something 2 is executed about $n$ times. As for do-something 1:

  • If $n < 5$, no times.
  • If $5 \leq n < (4/3)5$, $5$ times.
  • If $(4/3)5 \leq n < (4/3)^25$, $(4/3)5$ times.
  • Generally, if $(4/3)^k5 \leq n < (4/3)^{k+1}5$, $(4/3)^k5$ times.

Be creative and estimate the number of times that do-something 1 is executed in terms of $n$. Conclude the running time of the code snippet.

Yuval Filmus
  • 276,994
  • 27
  • 311
  • 503
-2

it can't be big theta because it has an escape clause, ie if this then don't do this. generally you would look for a loop through n values to be O(n) and two nested loops to be O(n^2), etc.

user39303
  • 1
  • 1