Union-Find Algorithms
Scientific method
Steps to develop a usable algorithm using scientific method:
Define the problem.
Find an algorithm to solve it.
Fast enough?
If not, figure out why.
Find a way to address the problem.
Iterate until satisfied.
Dynamic connectivity
Given set of N objects we support two operations:
Union command, that connects two objects
Find connected objects command, that fins if two objects are connected
Another connectivity example. 
Modeling the connections
If we connect 1 and 2, we need to recreate groups of connected points.
Quick-Find - eager approach
The elements are connected if the have the same number in an array.

Union
In order to union (connect the points) we need to change all from id[p] to id[q].

Java implementation
Cost model: initialize O(n), union O(n), find O(1). Takes n^2 array accesses to process sequence of N union commands on N objects. It is too slow and we can't accept that, quick-find is too slow.
It prints out:
Quick-union - lazy approach
We create tree structure. Before we connect two dots, we need to find root of the dot we want to connect to.
Here is an example of a tree with its array.
Java implementation:
Here is the output.
Quick-union is also slow. Intialize O(n), union O(n) - but N depends on depth of tree, if tree is too deep, algorithm will perform slowly, find O(n).
Quick-union improvements
Improvement 1: Weighting
Link root of smaller tree to root of larger tree.
Here is the result of weighting in bigger scope.
Java implementation:
Here is the output, observe how values are linked in the array.
Initialize O(n), union O(log2n), connect O(log2n).
Improvement 2: Path Compression
As we go up through the tree, we flatten the tree by putting the node below the root.
Java implementation (only this line ids[i] = ids[ids[i]]; has been added to root method).
Here is the output of that program.
Insert O(n), union(log2*n) - iterative logarithm, find O(log2n). Simply said, what would take 30 years to compute, it can be done in 6 seconds when using Weighted-Path-Compressed Quick-Union.
Percolation
Percolates if there is a way from to to bottom. This model is used in electricity, fluid flow, social interactions and so on.
Here is how we represent the model.
More about the problem to solve is here.
Last updated
Was this helpful?