Assignment 3 – Solution and Marking Scheme Problem 1 (Graded) Show that f(n) = 3n2 + 7 is O(n2). 3n2 + 7 <= 3n2 + 7n2 for n >= 1 <= 10 n2 Let c = 10, g(n) = n2, and n0 = 1=> f(n) is O(n2) Problem 2 (Graded) Determine the running time in term of Big-Oh of the following code fragment: public static void method(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); for (int i = 0; i < n; i++) System.out.println(a[i]); } 2 1 + n+1 + 2n = 3n 1 + n+1 + 2n = 2n 3n + 2 3n + 2 The running time T(n) is: 11n + 6 <= 11n + 6n <= 17n for n > 0. Let c = 17, g(n) = n, and n0 = 1 => f(n) is O(n) Problem 3 (Ungraded) Without showing the details, what is the time complexity of the following code fragment? Justify your answer. int i, j; System.out.print("Enter a number: "); int n = scan.nextInt(); for (i = 0; i < 100;i++) for (j = 0; j < 100;j++) { if (j == 50) break; else if(i == n) break; else { i = 100, j = 100; } } The time complexity of this algorithm is O(1). If n == 0 the inner loop will execute only once since i == n == 0 so in the first iteration of the inner loop break will be executed. The outer loop will execute twice since when i becomes 1 the body of the last else will execute and i becomes 100. So the total number of repetitions of the nested loops is 2*1 = 2. If n != 0 the inner loop will execute once since the body of the last else will execute and j becomes 100 The outer loop will also execute once since when I was also set to 100 in the last else. So the total number of repetitions of the nested loops is 1*1 = 1. Problem 4 (Ungraded) What is the time complexity of the following algorithm if we are using the big Oh notation? When is the best case? Show your detailed work. public static void method(int n, int x) { int m = n/2; 2 for (int i = 1; i <= n; i++) 1 + n+1 + 2n = 3n + 2 for (int j = 0; j <= m; j++) n(1 + m+2 + 2(m+1)) = 3mn + 5n = 3/2n2 + 5n if (x > 0) n(m+1) = n2/2 + n for (int k = 1; k <= n*n; k++)(n2/2 + n)(1 + n2+1 + 2n2) = 3/2n4 + 3n3 + n2 + 2n System.out.println(k); (n2/2 + n)n2 = n4/2 + n3 else for (int k = 1; k <= n; k++) (n2/2 + n)(1 + n+1 + 2n) = 3/2n3 + 4n2 + 2n System.out.println(k); (n2/2 + n)n = n3/2 + n2 } The best case is when x<=0 since the inner loop which repeats n times will be executed instead of the inner loop with which repeats n2 times. In the best case T(n) is O(n3). The worst case is when x>0 since the inner loop which repeats n2 times will be executed instead of the loop with which repeats n times. In the worst case T(n) is O(n 4). Therefore, the time complexity of the algorithm is O(n4).