Test 2 Compsci 100, Fall 2008 ------ Problem 1 -- Part A: The while is O(n) for an n-node list. The list is chopped in half, there are two recursive calls. So if T(n) = time for convert to run on an n-node list, then we have T(n) = 2T(n/2) + O(n). The solution to this is O(n log n) -- Part B: The purpose of middle.prev.next = null is to break the list into two pieces. Specifically it's to ensure that the recursive call to convert(first) succeeds since conver requires a null-terminated list for the while loop to work. Part C: We need to reconnect. Change the last line to these two lines: TreeNode ret = new TreeNode(middle.info,convert(first),convert(second)); middle.prev.next = middle; return ret; Part D: Inserting nodes from a sorted linked list into an unbalanced tree yields a tree that looks like a linked list, i.e., every node has one right child and no left children. Insertion into such an unbalanced tree is O(k) for an k-node tree. This yields 1 + 2 + 3 + ... + n for n-nodes in a linnked list which is O(n^2) Part E: An AVL tree has O(log n) cost for insert/delete/find since the tree is always balanced. This yields O(lg 1)+O(lg 2)+...+O(lg n) which is O(n log n) Problem 2: post: left,right, visit: --- Jaguar Hippo Monkey Lion Rhino Narwhal Part B: 11, # nodes in tree Part C: T(n) = 2T(n/2) + O(1) which is O(n) for balanced trees. Even for unbalanced we get T(n) = T(n-1)+O(1) which is O(n) Part D: Narwhal Part E: Method works because elements inserted into an arraylist using in-order traversal and are thus in sorted order. The array must be sorted for findKthArray to work. Complexity is O(n) for calling fill, fill is linear since it's in-order, visiting n nodes exactly once and doing O(1) work per visit. list.get(k) is O(1) so complexity is O(n) Part F: The method works because it stops when there are k elements in the left subtree meaning the root is bigger than k elements and is thus the k-th largest. The recursive calls ensure that k changes appropriately in the recursive call when there are fewer than k elements in the left subtree. Complexity: T(n) = T(n/2) + O(n) since size is O(n) and there's only one recursive call made. This is O(n) Problem 3: Part A: return o.runtime - runtime; if (runtime[k] > runtime[k+1]) Part B: Sort is O(n log n) this dominates and is the runtime Part C: O(n^2) this is the standard double-loop n-squared sort or more formally: 1+2+3+...+n Part D: both bubble and selection are O(n^2) so doubtful it's "much faster". However, it likely will be faster in practice, though not enough to warant discussion Problem 4: treeset contains is O(lg n) for an n-element set. Thus we get O(A log B) for intersect(seta, setb) and O(B log A) for intersect(setb, seta) these are very different, e.g., if A has a million elements and B has 10 Part B: For hashing contains is O(1) so answers will be different for each call, they'll be O(A) and O(B) for intersect(seta, setb) and swapping parameters, respectively.