EFFICIENCY QUESTIONS AND ANSWERS
What is the Bigoh of the following code snippets?
1. for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
1+1;
Answer: O(n^2)
Explanation: The outer for loop has i = 0…n making it run n. The inner for
loop has j = 0…n making it run n as well. Since the for loop with j is
nested, we multiply their run times to get n^2.
2. for(int i = 0; i < n; i++)
1+1;
for(int j = 0; j < n*n; j++)
1+1;
Answer: O(n^2)
Explanation: The loop with i runs from 0…n, making its runtime n. The
loop with j runs from 0…n^2, making its runtime n^2. However, since the for
loop with j is a separate loop, we merely add them together: n+n^2. We drop
the lower terms to get O(n^2).
3.
for(int i = 0; i < n*n; i++)
for(int j = 1; j <= i*n; j++)
for(int k = 0; k < j*j; k++)
for(int r = 0; r < i; r++)
1+1;
Answer: n^13
Explanation: The loop with i runs from 0…n*n, making it have a runtime of
n^2. For the loop with j, the runtime is i*n, but i is dependent on n (i =
n^2). Therefore, the loop with j has the runtime of n^3. The loop with k has
runtime j^2, but j = n^3, so the runtime of this loop is (n^3)^2 = n^6. The
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview.
Sign up
to
access the rest of the document.
 Fall '10
 Sweat,Monica
 Algorithms, Addition, Multiplication, Data Structures, Big O notation, Analysis of algorithms, Computational complexity theory

Click to edit the document details