CS367 Fall 2004: Homework 1 Solution
1. An algorithm with a constant running time as
n
increases.
assign n to temp
add 1 to temp
multiply temp by n
divide temp by 2
As n increases, there are always four operations.
2. The evaluation of the following nested loop is cubic O(n
3
) as n increases.
double sum = 0;
for ( int i=0; i < n; i++ )
for ( int j=0; j < n; j++ )
for ( int k=0; k < n; k++ )
sum++;
3. O(n
2
)
1+1 + 2+1 + 3+1 +.
..+ (n1)+(1) + n =
(n1)*1
+
1+2+3+4+.
..+(n4)+(n2)+(n1)+ n =
(n1)*(2/2)
+
n/2*(n+1) =
(2n2)/2
+
n*(n+1)/2 =
((2n2) + (n^2 + n + 1))/2 =
(2n  2 + n^2 + n + 1)/2 =
(n^2 + 3n  1)/2 =
O(n^2)
4. O(n
2
)
When n increases by a factor of 10, the number of cycles increases by a factor of 100. Therefore the
algorithm appears to be quadratic.
5. O(n) The red curve is linear, even though it has a very steep slope and intercepts the yaxis at
approximately 43.
6. O(n
2
)
7. O(log
a
n), where a can be any base.
8. O(n
5
)
9. O(n)
Notice that the running time varies linear with n.
10.O(n)
Adding an element to an arraybased list at the position indicated by getNumItems is the same as
adding to the next available element in the array. The complexity of getNumItems is constant time
and the add to end is constant also, except in the case where the array must be expanded. The loop
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Documentexecutes n times, so the complexity is O(n).
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '08
 MarvinSolomon
 Addition, Data Structures, Computational complexity theory, 3 pts, 4 pts, 0 PTS, #ops

Click to edit the document details