I am learning about BIG-O and got confused below:
int arr=[1,2,3,4,5]
-- simple print
print(arr[0])
print(arr[1])
print(arr[2])
print(arr[3])
print(arr[4])
-- loop - BIG-O O(n)
for i in length(arr) {
print( arr[i] )
}
would the simple print also give me O(n) or O(1) ?
CodePudding user response:
Big-O is all about loops and growth.
If you have a fixed n then it is O(1) to print them — it will always take the same amount of time (n=5) to print n=5 items.
But for some variable n, it takes more time the larger n gets, so it becomes O(n).
If you are talking about storage, then an array of n items is O(n), even for fixed n=5.
Context matters. This context was me being stupid. O(5) is O(1).
CodePudding user response:
Your print statement is constant (O(1)), because you are accessing a value by index, and indexed access of an array is typically a constant-time operation.
Your loop is O(n), as you guessed.
As a disclaimer, this can get more complex depending on our computation model and assumptions. For instance, not all computation model assume constant-time random access, and you could argue that printing a number also depends on the size of that number and turns out to be O(log n). But I think that in the scope of your question, you don't need to worry about this.