Reputation: 1
I have the following piece of code:
And I have the following questions on it:
Since I am quite new to algorithms and running times, I do not know if there are any rules I need to follow when answering this type of question on worst-case analysis or is it purely based on intuition?
For example for question C. I would say the answer is B = O(N).
Upvotes: 0
Views: 259
Reputation: 1885
Stackoverflow is not a homework solving platform. In order to receive decent answers on your problems, you need to provide at least some approaches you have tried.
Answering your question if there are any rules:
Yes there are (at least some rules of thumb). You basically need to try to find all computations that are done in relation to your input.
The typical example for O(n); size=n
is a single for loop:
for (int i = 0; i < size; i++) {
printf("%d\n", i];
}
Whereas O(n^2)
would represent e.g. an algorithm with two nested for loops.
For each i
you will run through n
which leaves you with n*n
iterations (where size = n
):
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("%d , %d\n", i, j);
}
}
Upvotes: 1