// Find, with path halving: avoids recursion public Eqclass <T> Find() { if (link == null) { return(this); } else if (link.link == null) { return(link); } else { // Grandparent, parent, and link Eqclass <T> pp = this, p = link, plink = p.link; while (plink != null) { // Invariant: pp -> p -> plink pp.link = plink; pp = p; p = plink; plink = p.link; } return(p); } }
public static Eqclass <T> Make(T item) { Eqclass <T> result; if (!dict.Find(item, out result)) { dict[item] = result = new Eqclass <T>(item); } return(result); }
public static void Main(String[] args) { Eqclass <int> x = Eqclass <int> .Make(3), y = Eqclass <int> .Make(4), z = Eqclass <int> .Make(5); x.Union(y); y.Union(z); Console.WriteLine(x.Find().Item); Console.WriteLine(y.Find().Item); Console.WriteLine(z.Find().Item); }
public void Union(Eqclass <T> that) { Eqclass <T> thatRep = that.Find(), thisRep = this.Find(); if (thatRep != thisRep) { if (thatRep.rank == thisRep.rank) { thisRep.link = thatRep; thatRep.rank++; } else if (thatRep.rank > thisRep.rank) { thisRep.link = thatRep; } else { thatRep.link = thisRep; } } }