Docsity

Java Programming: Sorting Colored Objects and Implementing Iterators, Exams of Computer Science

Partial preview of the text

Download Java Programming: Sorting Colored Objects and Implementing Iterators and more Exams Computer Science in PDF only on Docsity!

CS211, Fall 2004

Prelim 2 Solutions

PART A. Inheritance (14 points total)

Consider the following class definitions.

public class Pair { public String value; public String name; }

public class A {

private Pair x;

public A (String value) { x = new Pair(); x.value = value; }

public A () { x = new Pair(); x.name = ”A”; x.value = ”A”; }

final public String getValue () { return getx().value; }

final public void setValue (String value) { getx (). value = value; }

final public String getName () { return x.name; }

final public void setName (String name) { x.name = name; }

protected Pair getx () { return x; } }

public class B extends A {

PART B: Searching and Sorting (30 points total)

Consider an array of colored objects, where each object can be one of three colors (red, blue, or green) and there is at least one object of each color. Write down a function to sort the array of objects by color, with the red objects appearing before blue objects appearing before green objects. Your function should have an asymptotic time complexity of O(N), where N is the number of colored objects in the input array. Your sort should be “in-place” (like Quicksort), and should not require an extra array besides the input array. Hint: Consider extending the first phase of the Quicksort algorithm, where you partition the array based on the pivot value (What would be a good pivot value in this particular case? Is it necessary to recursively sort both partitions of the array?) When writing the code for your sorting function, you should use the classes given below. /∗∗ ∗ Class representing colored object ∗/ public class ColoredObject {

public static final int RED = 0; public static final int BLUE = 1; public static final in GREEN = 2;

private int color; private Object value;

public ColoredObject (int color, Object value) { this. color = color ; this.value = value; }

public int getColor () { return this.color; }

public Object getValue () { return this.value; } }

B.1) Write a function to sort an array of colored objects as per the specifications above. The function should have the following signature: void sort (ColoredObject arr[]). Recall that the algorithm should have time complexity O(N), where N is the number of colored objects in the input array. (30 points)

B.1) Solution: There are many possible solutions to this problem. Below are two major ap- proaches, each of which has variations. For example, in the quick-sort like one, one may pivot around the smallest element, in which case the recursive call will shift the beginning, not the end. Similarly, there is a symmetric variant of the second algorithm that fills stuff in from

the end. It is also possible to do something closer in spirit to counting sort, but then one would have to be careful not to undo any work.

Both routines below use the following helper:

void swap(ColoredObject[] arr, int a, int b) { ColoredObject tmp = arr[a]; arr [a] = arr [b ]; arr [b] = tmp; }

This is an approach using pivoting similar to quicksort, as in the hint, with some comments on possible variations:

//Sort the [0, end) portion; //note that if [0, end] is used, all the comparisons //with end and the recursive calls must be adjusted void sortAux(ColoredObject[] arr, int end) { if (end == 0) //alternatively, one can do an emptiness check when trying return; //to move the largest one to the end

//Find the largest object : to be used as a pivot ColoredObject largest = null; int largestIndex = −1; for (int i = 0; i < end; ++i) { //All sorts of optimizations are possible here to stop when the //maximum color is found, but they’re not that important if ( largest == null || arr [ i ]. getColor() > largest .getColor()) { largest = arr[i ]; largestIndex = i ; } }

//Possible optimization here : return if only one color.

// alternative emptiness check here //if ( largest == null) // return;

//Put the pivot in place swap(arr, largestIndex , end − 1);

//Now, do the ”collapsing walls” portion of the algorithm, //except we extend the right −hand portion to include //everything that equals to the pivot. int l = 0;

//passed by the i loop. if ( arr [ i ]. getColor() == color) { swap(arr, i , out); ++out; } }

//out now points one past the region of the color color : //that’s where the next color may start. sortAux(arr, color + 1, out); }

void sort(ColoredObject[] arr) { sortAux(arr, ColoredObject.RED, 0); }

B.1) Grading: • +4 pts: for comments that explain the approach taken, even if incorrect.

  • Implementation that are not linear in time should receive no correctness credit (but may receive comment credit), unless the complexity appears to be due to a bug and not flawed design.
  • +10 pts: if code or comments suggest something that’s akin to a working algorithm, but which would not actually come close to working; partial fraction of this should be given if the student seems to have understood the ideas underlying a solution, but not put them together into an overall shape of solution.
  • +26 pts: essentially a working algorithm, but may have bugs, which will have deductions as below (but this should not be deducted to below +10, as that’s the baseline for getting it but not implementing properly)
  • -10 pts: major bugs: portions of implementation mostly incorrect
  • -5 pts: substantial bugs that affect alogithm correctness
  • -2 pts: each off-by-one style error, including loop bounds (but not the pivoting and similar comparisons)
  • -2 pts: for each missing bound checks in the partitioning loop, if any.
  • -1 pts: if any minor syntax errors that could be considered typos (total, only one of these deductions should be made)

PART C: Asymptotic Complexity (20 points total)

C.1) Consider four functions f (n), g(n), d(n), h(n), which only return non-negative values. If f (n) is O(g(n)) and d(n) is O(h(n)), then f (n) · d(n) is O(g(n) · h(n)). Justify this by finding an appropriate witness pair. (7 points)

C.1) Solution: Since f (n) is O(g(n)), there is some witness pair (nf , cf ) such that for all n > nf , f (n) ≤ cf g(n). Likewise there is some witness pair (nd, cd) such that for all (nd, cd), it is the case that d(n) ≤ cdh(n).

Thus, if n > max(nf , nd), then n > nf so f (n) ≤ cf g(n), and n is also greater than nd, so d(n) ≤ cdh(n). Thus f (n) · d(n) ≥ cf cdg(n)h(n), so (max(nf , nd), cf cd) is an appropriate witness pair. There are other possible witness pairs, for example (nf + nd, cf cd), and students should get full credit for any valid witness pair with justification. However a student who does not define nf , nd and so on shall receive no more that 2 points. A student who defines these, but guesses something other than (max(nf , nd), cf cd) without any justification shall receive no more than 3 points.

C.2) Consider the following function:

public void test (int n) { int a = 0; for (int i=0; i <n∗n; i++) for (int j = 0 ; j <= i; j++) a = a + i ∗ j ; }

What is the asymptotic time complexity of this function? Briefly justify your answer. You will not receive credit without the proper justification. (7 points).

C.2) Solution: The running time of the inner loop is O(i). The running time for the outer loop is ∑n^2 i=

O(i) = O

( n^2 (n^2 + 1) 2

) = O(n^4 )

If the student just writes O(n^4 ) without some justification, no points shall be awarded. If the student sees that the inner loop runs for n^2 iterations and that the inner loop takes O(i) time, but gets the analysis wrong, then you may award up to 4 points.

C.3) Consider the following pseudocode:

public void test2 (array A) { if size of A is 0, 1 or 2 do some fixed amount of work; otherwise divide the array A into 3 equal parts , and call test2 recursively on each piece ; do work proportional to the size of the array A; }

Write down the recurrence equation for the running time of the following pseudo-code. ( points)

C.3) Solution:

T (0) = O(1) T (1) = O(1) T (2) = O(1) 1 point for these 3 above T (n) = 3 T (n/3) + O(n) 6 points

D.2) Create an iterator that traverses a binary tree in preorder. The constructor of the iterator should have time complexity O(1). Each invocation of the next() operation in the iterator should have time complexity O(h), where h is the height of the binary tree. To implement the iterator, you have to use the classes given below and implement the methods in the PreorderIterator inner class of the Tree class. Make sure that exceptions are handled and thrown correctly, as per the function signatures. Hint: Consider using the stack sequence structure in PreorderIterator to keep track of the current state of the iteration. Implement the stack using the ListCell class provided below.

D.2) Implement the PreorderIterator class as per the above specifications. Recall that the con- structor should have time complexity O(1) and the next() operation should have time com- plexity O(h), where h is the height of the binary tree. Also, make sure that you handle and throw exceptions correctly. (30 points). public class Tree {

private BinaryTreeNode root;

public Tree (BinaryTreeNode root, int height) { this.root = root; this.height = height; }

public Iterator preorderIterator () throws IteratorException { return new PreorderIterator(); }

/∗∗ ∗ The inner iterator class ∗/ private class PreorderIterator {

// add variables as required

public PreorderIterator() throws IteratorException { // implement this. }

public boolean hasNext() { // implement this. }

public BinaryTreeNode next() throws IteratorException { // implement this } } }

∗ The binary tree node interface. ∗/ public interface BinaryTreeNode { public Object getData() throws TreeException; public BinaryTreeNode getLeft() throws TreeException; public BinaryTreeNode getRight() throws TreeException; }

/∗∗ ∗ The iterator exception class ∗/ public class IteratorException extends Exception {

private String errorMessage;

IteratorException (String errorMessage) { this.errorMessage = errorMessage; }

String toString () { return this.errorMessage; } }

/∗∗ ∗ The tree exception class ∗/ public class TreeException extends Exception {

private String errorMessage;

TreeException (String errorMessage) { this.errorMessage = errorMessage; }

String toString () { return this.errorMessage; } }

/∗∗ ∗ The ListCell class ∗/ public class ListCell {

private Object datum; private ListCell next;

public boolean empty() { return tos == null; }

public void push(Object datum) { ListCell newCell = new ListCell(datum, tos); // reset top of the stack pointer tos = newCell; }

public Object pop() { if (empty()) return null;

Object retVal = tos.getDatum(); tos = tos.getNext();

return retVal; } }

/∗∗ ∗ The tree class ∗/ public class Tree { BinaryTreeNode root;

public Tree(BinaryTreeNode root) { this.root = root; }

public PreorderIterator preorderIterator () throws IteratorException { return new PreorderIterator(); }

/∗∗ ∗ The inner iterator class ∗/ protected class PreorderIterator { private Stack stack;

public PreorderIterator() throws IteratorException { stack = new Stack(); stack.push(root); }

public boolean hasNext() { return !stack.empty(); }

public BinaryTreeNode next() throws IteratorException { if (! hasNext()) return null;

// pop the current node BinaryTreeNode node = (BinaryTreeNode) stack.pop(); // push it ’s children on the stack if any, right first to respect the order try { if (node.getRight() != null) { stack.push(node.getRight()); } if (node.getLeft() != null) { stack.push(node.getLeft()); }

return node; } catch (TreeException e) { throw new IteratorException(e.getMessage()); } }

} }