
CPSC 212-301 Name: _____________________________
Test #3A December 4, 2006
Honor Pledge:
I pledge that I have neither given nor received unauthorized assistance on this test.
Signed: _______________________ Date: _____________
20 points. 50 minutes. Open Java API. You may not visit any other web page. You are to develop a class
called MyDisjointSet with one constructor:
public MyDisjointSet (int x[]) {
// ... your code ...
} // MyDisjointSet
where x[] represents a disjoint set as discussed in class and in your text. Index i is the root of a tree iff the
contents of x[i] is negative. The array x[] has been initialized. You may assume that there are no errors.
In class, we discussed the disjoint set operations of find and union by height. Complete the following
public methods (5 points each):
public int find(int u) { public void unionByHeight(int u, int v) {
// ... your code ... // ... your code ...
} // find } // unionByHeight
Recall that find(int u)returns the set (index) to which node u belongs. Note that this method need not
perform a smart find operation. The method unionbyHeight() takes the union of the two sets to which u
and v belong. You may discover that your find()method will be useful in your unionByHeight() method.
Write a toString() method (5 points) that returns a String containing the contents of the array.
public String toString() {
// ... your code ...
} // toString
The returned String should be neatly formatted so that the output looks something like:
i: 0 1 2 3 4 5 6 7
x[]: 6 2 4 4 -4 -2 -2 5
You may assume that the contents of the array are at most 2-digit numbers.
Finally, write a method (5 points) called treeStructure():
public String treeStructure () {
// ... your code ...
} // treeStructure
which returns a String that shows the dependences of the disjoint set.
For example, consider the disjoint set on the right
represented by the array x[] below:
i: 0 1 2 3 4 5 6 7
x[]: 6 2 4 4 -2 -1 -1 5