h1solution

h1solution - CS367 Fall 2004: Homework 1 Solution 1. An...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
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 +. ..+ (n-1)+(1) + n = (n-1)*1 + 1+2+3+4+. ..+(n-4)+(n-2)+(n-1)+ n = (n-1)*(2/2) + n/2*(n+1) = (2n-2)/2 + n*(n+1)/2 = ((2n-2) + (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 y-axis 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 array-based 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
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
executes n times, so the complexity is O(n).
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/17/2011 for the course CS 367 taught by Professor Marvinsolomon during the Spring '08 term at Wisconsin.

Page1 / 5

h1solution - CS367 Fall 2004: Homework 1 Solution 1. An...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online