/*
 *$Log$
 */

package general;

/**
 * Disjoint Set Element, used by Kruskal's algorithm to 
 * calculate minimum spanning tree
 */
public class DisjointSetElement {
  private DisjointSetElement parent;
  private Object element;
  private int rank ;

/**
 * create a Disjoint Set Element from an Object,
 * the elements can form a forest.
 * the parent of the element is itself,
 * so it's a tree by itself.
 * the rank is 0.
 */
  public DisjointSetElement(Object o) {
    element = o;
    parent = this;
    rank = 0;
  }

/**
 * unite two disjoint set forests. 
 * @return: nothing returned.
 * the root of a set with smaller rank points to root with 
 * larger rank.
 */
  public void union(DisjointSetElement y) {
    link( this.findSet(), y.findSet() );
  }

/**
 * used by union, to link two disjoint set forests.
 */
  private void link( DisjointSetElement x, DisjointSetElement y) {
    if ( x.rank > y.rank )
      y.parent = x;
    else
      x.parent = y;
    
    if ( x.rank == y.rank )
      y.rank = y.rank + 1;
  }

/**
 * find the root of this element.
 * it's a two pass method:
 * it makes one pass up the find path to find the root,
 * and it makes a second pass back down the find path to update each
 * node so that it points directly to the root.
 */
  public DisjointSetElement findSet() {
    if (this.parent != this)
      this.parent = this.parent.findSet();
    return this.parent;
  }
} // end of class DisjointSetElement






