6.2. Implementation
This sections discusses the implementation of disjoint sets.
Let us create the DisjointSet class:
public class DisjointSet {
private final int[] subsets;
public DisjointSet(int size) {
subsets = new int[size];
Arrays.fill(subsets, -1);
}
public DisjointSet(DisjointSet set) {
subsets = Arrays.copyOf(set.subsets, set.subsets.length);
}
}L2: the size of subset (-1implies1ID,-2implies2IDs, and so on).L5-6: every set is initialized with the size of1.L9: a copy constructor.
Let us define the find() method:
public int find(int id) {
return (subsets[id] < 0) ? id : find(subsets[id]);
}public int find(int id) {
return (subsets[id] < 0) ? id : (subsets[id] = find(subsets[id]));
}L2: returns the ID of the subset where the specific key belongs to.
What is the worst-case complexity of the
find()method?
We then define the inSameSet() method:
L2: returns true if the two specific keys are in the same set.
Finally, let us define the union() method:
L2-4: return the subset ID where bothkey1andkey2belongs to.L6-10: merges the set containingkey2to the set containingkey1.L11-15: merges the set containingkey1to the set containingkey2.
Last updated
Was this helpful?