Exam 1 Solutions 1. a. virtual bool removeLast(Elem&) = 0; b. bool removeLast(Elem& it) { //undebugged code if (rightcnt == 0) return false; Link* temp = fence; while (temp->next!=tail) temp=temp->next; temp->next = NULL; it = tail->element; delete tail; tail = temp; rightcnt--; return true; } OR: bool removeLast(Elem& it) { if (rightcnt == 0) return false; int saveleftcnt = leftcnt; Link* temp = fence; setEnd(); prev(); remove(it); setPos(saveleftcnt); return true; } 2. a. We know T(500) = c*500 for some c (approx), and T(500) = 2. So c = 2/500, and T(2000) = (2/500)*2000 = 8 sec. b. We know T(500) = c*500^2 for some c (approx), and T(500) = 2. So c = 2/250000, and T(2000) = (2/250000)*2000^2 = 32 sec. c. We know T(500) = c*500*log 500 = c*500*9 (approx), for some c, and T(500) = 2. So c = 2/4500, and T(2000) = (2/4500)*2000*11 = 88/9 = 10 (approx) d. We use the same c as in part b. The new algorithms's running time is (1/500000)*n^2. Equating (1/500000)*n^2 = 2, n^2 = 1000000, n = 1000. 3. a. Inner while loop: Theta(n) Outer loop: executed n times. Total: Theta(n^2) b. Inner while loop: Theta(1) because it's executed only 2 times Outer loop: executed n times. Total: Theta(n) c. Inner for loop: Theta(n), executed about n/2 times else clause: Theta(1), executed about n/2 times Total: Theta(n^2) + Theta(n) = Theta(n^2) d. if clause: Theta(1) because it's only executed when n < 10. else clause: Theta(1) Outer loop: executed n times Total: Theta(n) e. first loop: log n second loop: log n Total: Theta(log n) 4. a. T(n) = 1 for n < 10 T(n) = T(n/10) + 1 for n >= 10 b. T(n) = log_10 n + 1 (log_10 means log base 10) Exact when n is a power of 10, i.e., n = 10^k for some natural number k. c. Prove: when n is a power of 10, T(n) = log_10 n + 1. Base: n = 1. Then by the recurrence, T(1) = 1. Also, log_10 1 + 1 = 1, so we're done. Induction: assume n > 1 is a power of 10, and T(m) = log_10 m + 1 for all m < n that are powers of 10. By the recurrence, T(n) = T(n/10) + 1 = log_10 (n/10) + 1 + 1 by the induction assumption = log_10 n - 1 + 1 + 1 = log_10 n + 1 OR: Prove for all natural numbers k, T(10^k) = k + 1. Base: k = 0. Then T(10^0) = T(1) = 1 by the recurrence. Also, 0 + 1 = 1, so we're done. Induction assume k > 0, and T(10^{k-1}) = k. By the recurrence, T(10^k) = T(10^k/10) + 1 = T(10^{k-1}) + 1 = k + 1 by the induction assumption.