This question is for revision purposes from a past exam paper I just want to know if I am on the right track
1. int i=1;
2. while (i <= n) {
3. for (int j=1; j<10; j++)
4. sum++;
5. i++;
6. }
7. for( int j = 1; j <= n; j++ )
8. for( int k = 1; k <= n; k=k*2 )
9. sum++;
1.) How many times is statement 4 executed?
A. O(n)
B. O(n^2)
C. O(log n)
D. O(n log n)
E. none of the above
Here I chose A
2.) How many times is statement 9 executed?
A. O(n)
B. O(n^2)
C. O(log n)
D. O(n log n)
E. none of the above
Because of line 8 (k=k*2) I chose C
3.) What is the running time of the entire code fragment?
A. O(n)
B. O(n^2)
C. O(log n)
D. O(n log n)
Since O(n)+O(logn)=O(n) so I chose A
O(1) - Constant time complexity. O(n) - Linear time complexity. O(log n) - Logarithmic time complexity.
So, the time complexity is the number of operations an algorithm performs to complete its task (considering that each operation takes the same amount of time). The algorithm that performs the task in the smallest number of operations is considered the most efficient one in terms of the time complexity.
Time complexity represents the number of times a statement is executed. The time complexity of an algorithm is NOT the actual time required to execute a particular code, since that depends on other factors like programming language, operating software, processing power, etc.
Therefore, we would say that the best-case time complexity of insertion sort is O(n). A complexity of O(n) is also often called linear complexity.
Your answer 1 is correct, it's inside a loop controlled only by n
.
Answer 2 is incorrect. It would be O(log n)
if line 7 did not exist but, because line 7 is forcing lines 8 and 9 to run multiple times dependent on n
, the answer is O(n log n)
.
Answer 3 is the correct reasoning but suffers from the fact answer 2 was wrong. O(n) + O(n log n)
simplifies down to O(n log n)
.
So the answers are A
, D
and D
.
I dont know how the questions where formulated, but if the wording is like you say, your examiner didnt know the right definition of big O (at least when he expects the "right" answers) – as "Big O functions include smaller". So something that executes as a function of n in f(n) = 10 n which is linear is also in O(n), O(n^2), O(n log n). If one asks for the "smallest" possible, your answers would be
So if multiple answers were possible and it was just asked for how much it is executed, the right answers would be
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With