Say I wanted to perform complexity analysis from first principles on this simple loop –
for (int i = 0; i < n; i++)
{
a = i + 1;
}
Here is what I have done, is this the correct procedure or am I way off?
Initial assignment of 0 to i: 1 operation
Loop executed n times:
- Comparison of i to n: performed n+1 times
- Increment i: operation performed n times
- Assignment of i +1 to a: two operations performed n times
So total number of operations: 1 + (n+1) + n + 2n = 4n + 2
And this has Big Oh(n) complexity.
Is this correct? Is there a better way of doing it?
The final conclusion is correct, the algorithm is
O(n)However, when analyzing algorithms we usually avoid counting exactly how many ops are done, and look only for upper and lower bounds, since the exact details might be implementation dependent.
For example, in your code – loop-unrolling might decrease the number of compare ops in the code, and the exact number of ops you calculated is no exactly the number of ops done in practice.
Also, this assumes
ais anintor some primitive type, and theoperator=,operator+are done in constant time. Ifais for example some kind of big-integer, or string like, and you overloaded the operators – maybe eachoperator=isO(|a|), which makes the algorithmO(nlogn), orO(n^2), (or something else), depending on the specific implementation of the type ofa.