What is the time complexity of the following code?
void method1(int n){
for (int i = 0; i <arr.size()/2; i++){
System.out.println("");
}
}
What is the time complexity of the following code?
void method1(int n){
for (int i = 0; i <arr.size()/2; i++){
System.out.println("");
}
}
Because the number of iterations is proportional to the size of the array, this would be O(n). In general, you'll ignore any constant multiplications on the number of iterations in determining complexity.
You might find this useful: https://justin.abrah.ms/computer-science/how-to-calculate-big-o.html
I'm also guessing that this is a homework problem, so I would encourage you to contact your instructor or TA for additional help. Any good instructor is happy to spend whatever time is necessary to make sure that their students understand the material.
The complexity of this code depends on the number of time the loop will execute
let's assume the length of arr
is m
then the loop is going to execute m / 2
But the complexity is not O(m / 2)
instead it is O(m)
because we drop off constants when finding the complexity.