









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










Name: Solution Quiz Section: ___________________ TA: _______________________________ Student ID #: ___________________
1) Sorting Short Answer (15 points) a) (4 points) For each sorting algorithm below, give the asymptotic worst-‐case tight bound using “Big-‐O” notation. You should give the tightest and simplest bound possible. You do NOT need to explain your answer. Merge Sort Insertion Sort Selection Sort Heap Sort
2
2
b) (2 points) With a pivot rule of “always pick the element at index lo”, give an example array of numbers, where the length is at least length 6, that gives quick sort the worst-‐case runtime. What is this quick sort worst-‐case runtime using “Big-‐O” notation? 1 2 3 4 5 6 7 8 OR 8 7 6 5 4 3 2 1
2
c) (1 point) Briefly describe (in 1 sentence) a strategy discussed in lecture that makes quick sort pick a better pivot and avoid this worst-‐case runtime and get a better average runtime. Median of three: pick the median value of input[lo], input [(hi +lo)/2) and input[hi – 1] d) (1 point) Briefly explain, in 1-‐2 sentences, why we use a cut off for divide and conquer sorting algorithms like quick sort or merge sort. We use a cut off to stop our recursive calls. The overhead for recursion can be more expensive for small inputs of N, than a simple N^2 sort. e) (2 points) Can heap sort be done in place? If it can, briefly in 1-‐2 sentences, describe how. If it can’t, briefly in 1-‐2 sentences, describe why not. Yes. Every deleteMin() operation frees up one space in the array at the end of the heap values. You can insert the next min in that empty spot, and then reverse your input at the end (or use a max heap) to get sorted ascending order.
2) Sorting Code (10 points) Write Java code for a method mergeSection that takes two int[]s and indices lo (inclusive) and hi (exclusive) to perform the merge part of merge sort. The int[] input parameter, between lo and hi, stores two sorted sections (each section is half of the range from lo to hi). The int[] output parameter is the output array to merge the sorted sections into. After merge is called, the int[] output should store the result from merging the two sorted sections from the first array together. As with merge discussed in lecture, if the range between lo and hi has an odd length, the smaller sorted section will be the first half of the range. You may not make any extra data structures (has to be done with O(1) extra space). You may assume the array parameters are the same size and non-‐null. You may not make any other assumptions about the length of the array parameters. You may assume that lo and hi are valid indices and represent bounds on , but you may not make any assumptions about duplicate values in the int[] input. Four Examples (underlined parts of the input array showing sorted sections to merge): int[] input = { 2, 4, 6 , 1, 3, 5, 7 }; int[] output = {0, 0, 0, 0, 0, 0, 0, 0, 0}; mergeSection(input, output, 0, list.length); // after call, output: [1, 2, 3, 4, 5, 6, 7] int[] input = { 1, 3 , 2, 4 , 7, 1, 3, 5}; int[] output = {0, 0, 0, 0, 0, 0, 0}; mergeSection(input, output, 0, 4); // after call, output: [1, 2, 3, 4, 0, 0, 0, 0] int[] input = {5, 6, 7, 4 , 2, 3 }, int output = {0, 0, 0, 0, 0, 0} mergeSection(input, output, 3, 6 ); // after call, output: [0, 0, 0, 2, 3, 4] int[] input = { 1 }, int[] output = {0} mergeSection(input, output, 0, 1);
One solution: public static void mergeSection(int[] input, int[] output, int lo, int hi) { int i = lo; int mid = (lo + hi) / 2; int j = mid; int k = lo; while (i < mid && j < hi) { if (input[i] <= input[j]) { output[k] = input[i]; i++; k++; } else { output[k] = input[j]; j++; k++; } } while (i < mid) { output[k] = input[i]; i++; k++; } while (j < hi) { output[k] = input[j]; j++; k++; } }
c) (3 points) With up-‐trees represented as the up and weight arrays as described above, fill in the pseudocode for the union operation. Implement the union algorithm using the union by weight optimization described in lecture. If the pair of root nodes passed to your method are tied, resolve that tie by choosing the first parameter as the representative element. // Assuming x and y are root elements, perform a union of their sets // Assume you have access to int[] up and int[] weight void union(int x, int y) { if (x != y) { if (weight[x] < weight[y]) { weight[y] = weight[y] + weight[x]; up[x] = y; } else { weight[x] = weight[y] + weight[x]; up[y] = x; } } } d) (1 point) What is the next edge E that will be added to the MST by Kruskal’s algorithm? Write the edge as (u, v, n) , where u is one of the nodes, v is the other node, and n is the weight. (4, 5, 1) e) (1 point) What series of union and find operations will you do for this edge E to add it to your MST? Write them below as union(x, y) and find(x) , where x and y are values of nodes. int x = find(4); int y = find(5); if (x != y) { // optional if statement, part of Kruskal's algorithm to determine if edge to add union(x, y); } f) (1 point) Update the array representation and the diagram below after adding this edge E and updating the up-‐trees. There are two equally valid solutions. Do not do any optimizations. 1 2 3 4 5 up 3 -‐ 1 -‐ 1 1 3 weight -‐ 1 4 -‐ -‐ OR 1 2 3 4 5 up -‐ 1 -‐ 1 1 1 3 weight 4 1 -‐ -‐ -‐
4 ) Graph Analysis and Pseudocode (18 points) a) (1 point) What is the minimum number of edges possible in a connected undirected graph that does not have self edges? Give an exact answer, not in big-‐O notation, in terms of |V|. You do NOT need to explain. |V| -‐ 1 b) (7 points) Suppose a directed graph has k nodes, where each node corresponds to a number (1, 2, ..., k) and there is an edge from node i to node j if and only if i > j. I. (1 point) Draw the graph (using circles and arrows) assuming k = 4. II. (2 points) Draw both an adjacency matrix representation and an adjacency list representation of the graph assuming k = 4. If unsure about notation, clearly label your drawings to convey what your notation means for the graph representation. Adjacency Matrix: Adjacency List: 1 2 3 4 1 F F F F 2 T F F F 3 T T F F 4 T T T F
III. (1 point) In terms of k (if k is relevant), exactly how many edges are in the graph assuming an arbitrary value of k? 1 + 2 + 3 + 4 + ... + (k-‐1) or! !!!!! 𝑖 or many other ways to write this IV. (1 point) In terms of k (if k is relevant), exactly how many correct results for topological sort does this graph have assuming an arbitrary value of k? 1 V. (1 point) Is this graph (CIRCLE ONE): (1) strongly connected (2) weakly connected (3) unconnected VI. (1 point) Is this graph (CIRCLE ONE): (1) dense (2) sparse
5 ) Dijkstra’s Algorithm (11 points) Using the following graph: a) (5 points) Use Dijkstra’s algorithm with start node A to find the cost of the shortest path from A to each other node. For each node, record the cost and the previous node in the path. Keep track of the order you mark each node known for part (b).
b) (1 point) In what order would Dijkstra’s algorithm mark each node as known? A, C, D, E, H, F, B, G c) (1 point) Using Dijkstra’s algorithm, what is the shortest cost path from node A to node G and what is it’s cost? A -‐> D -‐> G cost of 9
d) (2 points) Are any of the paths computed in part (a) incorrect? For each path that has an incorrect cost, write the correct lowest-‐cost path and explain why it was incorrect. Yes, the cost to F is incorrect because of the negative edges. The shortest cost path found by Dijkstra's is A -‐> C -‐> F, with a cost of 5, but the actual shortest cost path is A -‐> B -‐> F with a cost of 4. e) (1 point) Do self edges break Dijkstra’s algorithm? Briefly explain, in 1-‐2 sentences, why or why not. No. If the self edge is not negative, it does not affect Dijkstra's algorithm. Dijkstra's algorithm doesn't consider nodes that are already marked known, so self edges would never be considered. f) (1 point) The graph repeated for reference: Is it possible to do a topological sort of the above graph? Briefly explain, in 1-‐2 sentences, why or why not. No. This is not a DAG. There is a cycle from C -‐> D -‐> E.
7 ) Topological Sort (6 points) a) (2 points) If possible, list two valid topological orderings of the nodes in the graph above. If there is only one valid topological ordering, list that one ordering. If there is no valid topological ordering, state why one does not exist. A, B, C, D, E A, C, B, D, E b) (3 points) Given a Vertex v that has just been added to the topological ordering and a Map<Vertex, Integer> inDegree storing the state of the in-‐degrees for each node still to be processed in the topological sort algorithm (before adding v to the output ordering), perform the update step to inDegree to reflect that v has been processed. // For graphData, each Vertex a is mapped to a set containing // Vertex b , if there is an edge (a, b) in the graph. Map<Vertex, Set
8 ) Design Decisions (6 points) For each of the following graph-‐based computational tasks, specify the type of graph most appropriate for the data in question in terms of undirected or directed , and unweighted or weighted. In addition, choose the graph algorithm from the following list best suited to computing a solution:
10 ) Problem Solving and Algorithms (10 points) Given two input arrays of integers, write pseudocode to determine if one array is an exact shuffle of the other array. A shuffle is defined as containing exactly the same elements in potentially different locations. You may write java code or pseudocode. Your pseudocode should resemble real code structure and syntax. You will solve this question 2 times.
a) (5 points) Solution 1 (optimize for runtime): boolean runtimeOptimizedIsShuffle(int[] list1, int[] list2) { Map<Integer, Integer> counts = new HashMap<Integer, Integer>(); for (int value : list1) { if (!counts.containsKey(value)) { counts.put(value, 0); } counts.put(value, counts.get(value) + 1); } for (int value : list2) { if (!counts.containsKey(value)) { return false; } counts.put(value, counts.get(value) – 1); } for (int value : counts.keySet()) { if (counts.get(value) != 0) { return false; } } return true; } O(N) space and O(N) runtime b) (5 points) Solution 2 (optimize for space): boolean spaceOptimizedIsShuffle(int[] list1, int[] list2) { Arrays.sort(list1); Arrays.sort(list2); return Arrays.equals(list1, list2); } O(1) space and O(N log(N)) runtime An alternate cute solution that doesn't modify the lists: boolean spaceOptimizedIsShuffle(int[] list1, int[] list2) { for (int domainValue : list1) { int count1 = 0; for (int i = 0; i < list1.length; i++) { if (list1[i] == domainValue) { count1++; } } int count2 = 0; for (int i = 0; i < list2.length; i++) { if (list2[i] == domainValue) { count2++; } } if (count1 != count2) { return false; } } return list1.length == list2.length; } O(1) space and O(N^2 ) runtime You're done! Yay!