Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big-O complexity java

Tags:

java

big-o

I'm new to Java, my question is on big-O complexity.

For a), it is clearly O(n^2) for a nested loop.

for ( int i = 0; i < n; i++)
    for ( int j=0; j < n; j++ )

however, for b), with sum++ operation at the end, and complications in the nested loop, does that change the its Big-O complexity at all?

int sum = 0;
for ( int i = 1; i <= n; i++)
    for ( int j = n; j > 0; j /= 2)
        sum++;
like image 783
Katherine Avatar asked May 13 '15 08:05

Katherine


People also ask

What is the complexity of Big O?

O(log n) - Logarithmic Complexity The time taken increases with the size of the data set, but not proportionately so. This means the algorithm takes longer per item on smaller datasets relative to larger ones. 1 item takes 1 second, 10 items takes 2 seconds, 100 items takes 3 seconds.

What is the big O in Java?

Big O describes the set of all algorithms that run no worse than a certain speed (it's an upper bound) Conversely, Big Ω describes the set of all algorithms that run no better than a certain speed (it's a lower bound) Finally, Big Θ describes the set of all algorithms that run at a certain speed (it's like equality)

What is O n time complexity in Java?

Here, i: It is a loop variable. n: Number of times the loop is to be executed. In above scenario, loop is executed 'n' times. Therefore, time complexity of this loop is O(n).


1 Answers

In your second example, the first for iterate n times, and the second iterate log2(n) times, since you divide j by 2 in each iteration. Therefore, the complexity is O(n log2 n).

sum++ in the last line does not affect the complexity.

like image 154
ntalbs Avatar answered Sep 21 '22 18:09

ntalbs