I am trying to learn how to work out worst case run time complexity and I was wondering if someone could explain in detail how to work it out for the code below by highlighting all the operations etc.... Sorry for the awful code example, I'm very aware it is the most pointless method ever!
public int two(int[] n){
int twosFound=0;
int other=0;
for (int i = 0; i < n.length; i++) {
if (n[i]==2) {
System.out.println("2 is found");
twosFound++;
}
else other++;
}
return twosFound;
}
Start with the basic building blocks, and then work your way upwards:
int
variable does not depend on the array length, therefore it is O(1).n
when you want to talk about O(n). This can easily lead to confusion.) n.length
takes constant time. On the other hand, if n
were a linked list or some other data structure, you would have to further analyze it.n[i]
takes constant time.System.out.println
takes constant time, since it neither depends on the array length nor on the array contents. int
variable takes constant time.if
statement takes the worst of whatever its components take; in this case it is constant time.for
loop iterates linearly over the array, therefore it takes O(n.length), multiplied with O( whatever happens inside the body of the for
statement ). The time complexity if O(n) (actually, exactly n ) because control accesses all n elements of the array. (plus there are no extra conditions to terminate the loop)
Your worst case complexity does not differs from the other cases. Its because of your algorithm. Its running time is solely dependent on the number of elements in the array. You test each element to satisfy a condition, the more elements you have the longer it will take the algo to run.
In fact it clear that time complexity is O(number_of_elements) . It means that time is linear dependent on the number of elements. If you take twice bigger array the time will also increase twice.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.