The Union Find data structure.
Inspiration has been gotten from the book Algorithms by Robert Sedgewick and Kevin Wayne.
There are a number of easy ways to improve the union-find algorithm. Ideally, we would like every node to link directly to the root of its tree, but we do not want to pay the price of changing a large number of links. We can approach the ideal simply by making all the nodes that we do examine directly link to the root.
The amortized cost per operation for this algorithm is known to be logarithmic.
Add connection between two elements.
"""
unionFind : UnionFind
unionFind =
quickUnionPathCompression
|> union 0 1 -- creates connection between 0 and 1
|> union 1 2 -- creates connection between 1 and 2
|> union 0 2 -- already connected
"""Given an element, returns the "parent" of the element.
"""
parentOf0 : Int
parentOf0 =
quickUnionPathCompression
|> union 0 1
|> get 0 -- would be equal 1
parentOf2 : Int
parentOf2 =
quickUnionPathCompression
|> union 0 1
|> get 2 -- would be equal 2
"""Given an element, returns the leader identifying the component to which the element belongs.
"""
leaderOf0 : Int
leaderOf0 =
quickUnionPathCompression
|> union 0 1
|> union 1 2
|> find 0 -- would be equal 2
"""Given two elements, returns True when both are in the same component.
"""
elements0and3AreConnected : Bool
elements0and3AreConnected =
quickUnionPathCompression
|> union 0 1
|> union 1 2
|> union 3 2
|> connected 0 3 -- would be equal True
elements0and3AreNotConnected : Bool
elements0and3AreNotConnected =
quickUnionPathCompression
|> union 0 1
|> union 1 2
|> union 3 4
|> connected 0 3 -- would be equal False
"""
Representation of Union Find data structure. You can create Union Find of any comparable primitives.