Reputation: 3021
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!
Upvotes: 6
Views: 4230
Reputation: 10789
Cubic complexity - three nested loops:
foreach
foreach
foreach
// actions
end
end
end
Logarithm complexity example - binary search.
Upvotes: 1
Reputation: 12706
O(n^3) can be represented by 3 nested loop.
O(log n) is represented by a loop which each iteration, the amount of data that need to be processed is reduced by half.
Upvotes: 0
Reputation: 212979
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.
Upvotes: 9
Reputation: 62504
Upvotes: 1
Reputation: 62439
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.
Upvotes: 5