Why isn't every algorithm O(1)?
TL;DR: Because the Big O
notation is used to quantify an algorithm, with regards of how it behaves with an increment of its input.
Informally, you can think about it as a framework that humans have invented to quantify classes of algorithms. If such framework would yield for every algorithm O(1)
, it would have defeated its own purpose in the first place i.e, quantify classes of algorithms.
More detailed answer
Let us start by clarifying what is Big O
notation in the current context. From (source) one can read:
Big O notation is a mathematical notation that describes the limiting
behavior of a function when the argument tends towards a particular
value or infinity. (..) In computer science, big O notation is used to classify algorithms
according to how their run time or space requirements grow as the
input size grows.
The following statement is not accurate:
But, I claim we can do this in O(1). why? we know for sure that n is locked in some field (since it's int and int is finite) which means I can sum all elements in less than 2,147,483,647 steps?
One cannot simply perform "O(2,147,483,647)" and claim that "O(1)" since the Big O
notation does not represent a function but rather a set of functions with a certain asymptotic upper-bound; as one can read from source:
Big O notation characterizes functions according to their growth
rates: different functions with the same growth rate may be
represented using the same O
notation.
Informally, in computer-science time-complexity and space-complexity theories, one can think of the Big O
notation as a categorization of algorithms with a certain worst-case scenario concerning time and space, respectively. For instance, O(n)
:
An algorithm is said to take linear time/space, or O(n) time/space, if its time/space complexity is O(n). Informally, this means that the running time/space increases at most linearly with the size of the input (source).
So the complexity is O(n)
because with an increment of the input the complexity grows linear and not constant.