DisjointSet - int rootB = find(indexB); i // Attach tree A...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
// Arup Guha // 9/25/09 // Written for Exam #1 question for COP 3503H Fall 2009 / // Just stores a pair of values associated with an item in a disjoint set. class Pair { c public int value; public int height; p public Pair(int v, int h) { value = v; height = h; } } public class DisjointSet { p // This array stores our data structure. private Pair[] parentList; p // Initialize each item to a value from 0 to n-1 all with a height of 0, meaning separate trees. public DisjointSet(int n) { parentList = new Pair[n]; for (int i=0; i<n; i++) { parentList[i] = new Pair(i,0); } } // Returns the value that is the root of the tree that stores value. public int find(int value) { p // Continue going up the ancestral tree until you get to a node without a parent. while (parentList[value].value != value) { value = parentList[value].value; } // Return this root. return value; } // Create a union between the tree storing indexA and the one storing indexB. // Precondition: the values indexA and indexB are stored in different subtrees. public void union(int indexA, int indexB) { p // Get each respective root node. int rootA = find(indexA);
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: int rootB = find(indexB); i // Attach tree A to be a child of tree B since A is shorter. if (parentList[rootA].height &lt; parentList[rootB].height) { parentList[rootA].value = rootB; } else { e // Attach B to be the child of A. parentList[rootB].value = rootA; p // If the trees are equal height, then A's root goes up 1 in height. if (parentList[rootA].height == parentList[rootB].height) parentList[rootA].height++; } } // For debugging purposes. Prints out the parent and height of each node. public void print() { for (int i=0; i&lt;parentList.length; i++) { System.out.print(parentList[i].value+&quot;\t&quot;); } System.out.println(); S for (int i=0; i&lt;parentList.length; i++) { System.out.print(parentList[i].height+&quot;\t&quot;); } System.out.println(&quot;\n&quot;); } // My simple test. public static void main(String args) { p DisjointSet d = new DisjointSet(10); D d.union(2,5); d.union(3,7); d.union(3,8); d.print(); d.union(1,9); d.union(8,9); d.print(); d.union(9,5); d.print(); d.union(0,7); d.print(); d.union(4,6); d.print(); } }...
View Full Document

This document was uploaded on 11/09/2009.

Page1 / 2

DisjointSet - int rootB = find(indexB); i // Attach tree A...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online