Is the logarithmic complexity represented by a loop?

as I understand it, linear complexity can be represented as a simple loop, and quadratic complexity can be represented as a nested loop. How can you imagine cubic and logarithmic complexity?

Thanks!

+6
source share
5 answers

A simple loop can have logarithmic complexity, for example

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

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

+9
source

Since the cube is O (n ^ 3), it will be three nested loops.

Logarithmic is not so simple and usually requires a recursive relationship. For example, MergeSort is O (n * log (n)), because it forms a recursion tree with a height of log (n), and merge operation O (n) is required for each level.

+5
source
  • Cubic - three nested loops
  • Logarithmic is the idea that on each cycle of the cycle you break the input data specified in parts (or somehow reduce them), and in the next cycle - a reduced data set, so basically the complexity does not increase significantly, and the input data grows increases. For example, look at the BinarySearch algorithm or any other Divide and Win .
+1
source

Cubic complexity - three nested cycles:

 foreach foreach foreach // actions end end end 

An example of logarithm complexity is binary search .

+1
source

O (n ^ 3) can be represented by three nested loops.

O (log n) is represented by a cycle in which each iteration, the amount of data that needs to be processed, is reduced by half.

0
source

Source: https://habr.com/ru/post/1380618/


All Articles