I am new in the algorithm analysis domain. I read here in the Stack Overflow question
"What is a plain English explanation of "Big O" notation?" that O(2n^2)
and O(100 n^2)
are the same as O(n^2)
. I don't understand this, because if we take n = 4, the number of operations will be:
O(2 n^2)
= 32 operationsO(100 n^2)
= 1600 operationsO(n^2)
= 16 operations
Can any one can explain why we are supposed to treat these different operation counts as equivalent?
Because it is a classification, so it places algorithms in some complexity class. The classes are O(1), O(n), O(n log n), O(n ^ 2), O(n ^ 3), O(n ^ n), etc. By definition, two algorithms are in the same complexity class if the difference is a constant factor when n goes to infinity (the big-oh notation is for comparing algorithmic complexity for large values of n).
Why this is true can be derived directly from the formal definition. More specifically,
f(x) = O(g(n))
if and only if|f(x)| <= M|g(x)| for all x >= x0
for someM
andx0
. Here you're free to pickM
as you wish, so ifM = 5
forf(x) = O(n2)
to be true, then you can just pickM = 5*100
forf(x) = O(100 n2)
to be true.Why this is useful is a bit of a different story.
Some concerns with having constants matter:
Big-O (which is part of asymptotic complexity) avoid all of these issues. You only check how many times some piece of code that takes a constant amount of time (i.e. independent of input size) is executed. As example:
So there are 4 multiplications, 1 subtraction and 1 addition, each executed n3 times, but here we just say that this code:
runs in constant time (it will always take the same amount of time, regardless of how many elements there are in the array) and will be executed
O(n3)
times, thus the running time isO(n3)
.Because
O(f(n))
means that the said function is bouded by some constant timesf(n)
. Ifg
is bounded by multiple of100 f(n)
, it is also bouded by multiple off(n)
. Specifically,O(2 n^2)
does not mean it's not greater than 16 forn = 4
, but that for alln
it's not greater thanC * 2n^2
for some fixedC
, independent ofn
.