I need help understanding/doing Big O Notation. I understand the purpose of it, I just don\'t know how to \"determine the complexity given a piece of code\".
These examples are fairly simple. First what you have to do is to determine the main (simple) operation in the code and try to express the number of invocations of this operation as a function of input.
To be less abstract:
a.)
This code always runs in a constant time. This time is dependant on the computer, I/O latency, etc. - but it is almost not dependant on the value of n
.
b.)
This time a piece of code inside a loop is executed several times. If n
is two times bigger, what can you say about the number of iterations?
c.)
Again some code inside a loop. But this time the number of iterations is less than n
. But if n
is sufficiently big, do you simmilarity to b.)?
d.)
This code is interesting. The operation inside a first loop is more sophisticated, but again it takes more-or-less constant amount of time. So how many times is it executed in relation to n
? Once again compare with b.)
The second loop is there only to trick you. For small n
it might actually take more time than the first one. However O(n) notation always takes high n
values into account.
5.)
The last piece of code is actually pretty simple. The number of simple operations inside a loop is equal to n^2
. Add 1
to n
and you'll get twice as much operations.