Revision Session1

# Revision Session1 - What is the complexity? s = 0; for...

This preview shows pages 1–2. Sign up to view the full content.

1 Revision Session 3 Oct 2007 3pm What is the complexity? ……… 2n i s = 0; for (i=1;i<=2n;i++) s = s+i; O(n) O(n 2 ) ……… ……… ……… ……… ……… ……… ……… ……… ……… 2n 2n i j inner loop of unique indices (i,j) s = 0; for (i=1; i <= 2n; i++) for (j=1; j <= i; j++) s = s + j; 2 Number of shaded squares = (n 2 )(n 2 )/2 = O(n 4 ) ……… ……… ……… ……… ……… ……… ……… ……… ……… n 2 n 2 i j s = 0; for (i=1;i<=n*n;i++) for (j=1;j<=i;j++) s = s+j; Number of shaded squares = ½ (n * n) = O(n 2 ) ……… ……… ……… ……… ……… ……… ……… ……… ……… n n i j s = 0; for (i=1;i<=n;i++){ if ((i%2)== 0) for (j=1;j<=n;j++) s = s+j; else s++; } s = 0; for (i=1;i<=2n; i = i * 2) s = s+i; s = 0; for (i=2n ;i > 0; i = i / 2) s = s+i; 3 s = 0; for (i=2n ;i > 0; i = i / 13) s = s+i; • Single recursion, easy: – n recursive calls, since n decreases by 1 each time, so O(n). int getMin(int[] A, n) { if (n==1) return A[0]; int min_int = getMin(A,n-1); int x = A[n-1]; if (x < min_int) min_int = x; return min_int; } int f(int n) { if (n<=1) return 1; else return f(n-1)+f(n-1); } • Multiple recursion, not so easy: – Each f(n) spawns two f(n-1) calls. – Total time = 1+2+4+…+2 n-1 = (2 n -1) = O(2 n ). f(n) f(n-1) f(n-1) f(n-2) f(n-2) f(n-2) f(n-2) 1=2 0 2=2 1 4=2 2 #recursive calls per level 8=2 3 …… f(1) f(1) f(1) f(1) f(1) f(1) 2 n-1 4 int f(int n) { if (n<=1) return 1; else return f(n/2)+f(n/2); } int f(int n) { if (n<=1) return 1; else { int s = 0; for (int i=0; i<n; i++) s++; return f(n/2)+f(n/2); } } int f(int n) { if (n<=1) return 1; else { int s = 0; for (j = 0; j < n; j++) for (int i=0; i<n; i++) s++; return f(n/2)+f(n/2); } } Which of the following statements about Binary Search is TRUE? A. The values need not be sorted for Binary Search to work. B. In the worst case, the number of comparisons in Binary Search is about the same as the number of comparisons in Linear Search. C. Binary Search can only be implemented using recursion.

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.

## This note was uploaded on 08/02/2009 for the course ECE CS1102C taught by Professor Dr.tansuntuck during the Spring '07 term at National University of Singapore.

### Page1 / 2

Revision Session1 - What is the complexity? s = 0; for...

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

View Full Document
Ask a homework question - tutors are online