What would the Big O notation be for two for loops that aren't nested?
Example:
for(int i=0; i<n; i++){
System.out.println(i);
}
for(int j=0; j<n; j++){
System.out.println(j);
}
This simple example has two 'for' loops, and for each element 'N' it will execute 'N' times. So in total it will execute N^2 times. In big O notation we would say that this algorithm has a complexity of O(N^2).
3. for (j = 0; j < N; j++) g(k); Each time through the loop g(k) takes k operations and the loop executes N times. Since you don't know the relative size of k and N, the overall complexity is O(N * k).
An example of an O(2n) function is the recursive calculation of Fibonacci numbers. O(2n) denotes an algorithm whose growth doubles with each addition to the input data set. The growth curve of an O(2n) function is exponential - starting off very shallow, then rising meteorically.
The big O of a loop is the number of iterations of the loop into number of statements within the loop. Now according to the definition, the Big O should be O(n*2) but it is O(n).
Also, use proper indentation to show that they are nested. first loop run n times.. 2nd loop runs n^2 times... 3rd loop runs n^3 times because they are all nested. But sometimes I think that its Big O notation is 1+2+3=6 i.e. O (n^6)
in the above example algorithm, we have two nested for loops. and in the first nested for loop, we have three two inners for loop and in the second we have one inner for loop. so the complexity of the algorithm is n 3 + n 2 In the above example algorithm, we have one nested for loop so in simple terms the algorithm has an order of n 2
Big O Notation refers to a mathematical function applied in computer science to analyze an algorithm’s complexity. It defines the runtime required for executing an algorithm, but it won’t tell you how fast your algorithm’s runtime is. Instead, it will help you identify how your algorithm’s performance will change with the input size.
Your mistake is with the inner loop. It does something constant n times, so it is O (n). The outer loop does the inner loop n times, so it is O (n × n), or O (n2).
Linear
O(n) + O(n) = 2*O(n) = O(n)
It does not matter how many non nested loops do you have (if this number is a constant and does not depends on n
) the complexity would be linear and would equal to the maximum number of iterations in the loop.
Technically this algorithm still operates in O(n) time.
While the number of iterations increases by 2 for each increase in n
, the time taken still increases at a linear rate, thus, in O(n) time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With