July 01, 2014

UnionFind for Dynamic connectivity

Union Find is used to find the connection between two objects.
Why do we need Union Find algorithm?

There are three approaches to implement this each with it's own complexity.
1. Quick Find:
Simplest but does union is quadratic in nature
2. Quick Union:
Union is Linear time but find also becomes linear which is constant in Quick find
3. Weighted QuickUnion:
Union and find are logarithmic in nature

Implementation:
The class diagram of my implementation uses code from Dr.Robert Sidgewich's code base. Here I use the template method and strategy pattern to do a quick comparison of performance of all the three types.
The following images show how the implementation is done.
UF is the abstract class from which all other union find classes inherit



UFclient uses the strategy pattern by invoking run() from the main factory method.

QuickFind inherits from UF and uses a single array with a simple idea to find connectivity as shown below.

 QuickUnionUF inherits from UF and uses a single array with tree structure to find connectivity as shown below.

QuickUnionUF inherits from UF and uses a single array with tree structure to find connectivity as shown below. It goes one step further to use a second array for maintaining and balancing weight on the tree.


Performance:

Significant performance difference can be observed from the output as shown below

Time taken for QuickFindUF is 177
Time taken for QuickUnionUF is 66
Time taken for WeightedQuickUnionUF is 25

You can see the difference between Quadratic vs Linear vs Logarithmic time. They are in the ratio 7:3:1

No comments:

Post a Comment