Example: Measuring Time Complexity of a Single Loop Algorithm
Understand how to measure the time complexity of a single loop algorithm in Java by counting primitive operations. Learn to evaluate each part of the loop, including initialization, increments, and comparisons, to derive the total runtime formula for effective asymptotic analysis.
We'll cover the following...
A for loop with n iterations
Now, let’s consider what happens when a loop is involved. Consider the following Java program::
Let’s count the number of primitive operations in the above program. First, look at lines 4 and 5 where variable initializations are taking place. These account for one primitive operation, each.
Line 6 is a loop statement. To count the number of primitive operations on that line, we must dissect it into its constituents: the initialization, the increment, and the test. The initialization occurs only once and is counted as one primitive operation. The increment () operation must read the current value of variable , add to it, and store the result back in variable . That’s three primitive operations. The test operation () must read ...