Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #187 Disjoint Set

Disjoint Sets hold elements that are partitioned into a number of disjoint (non-overlapping) sets.

public class DisjointSetElement {
  private DisjointSetElement representative = this;

  public DisjointSetElement getRepresentative() {
    if (representative != this) {
      representative = representative.getRepresentative();
    }
    return representative;
  }

  public void union(DisjointSetElement other) {
    other.getRepresentative().representative = getRepresentative();
  }
}
  

The class is usually subclassed with each element holding information about that specific element, and information about the aggregated set. The aggregated information is only used on the representative node

New implementation...
< >
Shaftway