Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logarithmic complexity represented with loop?

as far as I got it linear complexity can be represented as simple loop and quadratic complexity can be represented as nested loop. How can the cubic and logarithmic complexity be represented?

Thanks!

like image 386
Sergej Popov Avatar asked Nov 10 '11 16:11

Sergej Popov


2 Answers

A simple loop can have logarithmic complexity, e.g.

for (i = 1; i <= N; i *= 2)
    ...

As others have already answered, a triple nested loop will have cubic complexity.

like image 198
Paul R Avatar answered Oct 21 '22 09:10

Paul R


Since cubic is O(n^3), it would be three nested loops.

Logarithmic is not so straightforward and usually requires a recursive relation. For example, MergeSort is O(n*log(n)) because it forms a recursion tree of height log(n) and each level requires an O(n) merging operation.

like image 25
Tudor Avatar answered Oct 21 '22 08:10

Tudor