In this answer,it said that:
An algorithm is said to run in linear time if its time execution is directly proportional to the input size, i.e. time grows linearly as input size increases.
I have input a 3x3 array.So I need to input 9 numbers.It need 9 times to iterate.
I have input a 4x4 array.So I need to input 16 numbers.It need 16 times to iterate.
........
The execution of iteration is directly proportional to the amount of numbers(or the size).
So I think the time complexity should be O(n)
.
But another answer said that:
O(n^c): Time complexity of nested loops is equal to the number of times the innermost statement is executed. For example the following sample loops have O(n^2) time complexity
for (int i = 1; i <=n; i += c) {
for (int j = 1; j <=n; j += c) {
// some O(1) expressions
}
}
I feel a little confused. So I think the question can also be:
What is the mean of n
in array?(Does it means the size of the array or the dimension of the array?)What's the time complexity of use for
loop to iterate 2D array.
Is it O(n)
or O(n^2)
?
If the time complexity is O(n^2)
due to it have two for
loops.
I use this to create a 3x3 array:
a[0,1,2] -> b[0,1,2] -> c[0,1,2]
So I use it to iterate this arrays.It will be O(n)
,So it will faster than using for
loop to iterate the arrays.Why?
PS:I use Google translation to see those answer,so maybe I misunderstand it.