Implementation of Union-Find
Implementation of Union-Find uses an Array or Array-List of integers.
At the beginning, when all sets are disjoint we have that array list
contain -1 for every element. This -1 represents two different things.
The fact that it is negative tells us that this is the name of the set
(like 0 in the previous page). The 1 part of -1 tells us there is 1
element in the set. (Thus -2 would tell us there were 2, -3 that there
were 3, ...). Let us repeat our previous example using this notation.
We start with:
0
|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
-1
|
-1
|
-1
|
-1
|
-1
|
-1
|
-1
|
-1
|
-1
|
Unions make one set "point" to another by putting the index of the
other set in its place and replacing the parent with the negative of
the total number of elements in the set. For example, Union(3,0) would
change the value at 0 to -2 (the total number of elements in the set)
and the value at 3 to 0 (so it "pointed to" 0). This would yield:
0
|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
-2
|
-1
|
-1
|
0
|
-1
|
-1
|
-1
|
-1
|
-1
|
If we now did Union(3,2) Find(3) would transfer to 0 and since 0 now
has a negative the Find(3) would be 0. Find(2) would give 2 since 2
contains a negative. Thus we want to union 2 with 0. Since 0 is a more
negative number, we make 2 point to 0 and increase 0's negative value
to -3.
0
|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
-3
|
-1
|
0
|
0
|
-1
|
-1
|
-1
|
-1
|
-1
|
Similarly, Union(4,1) would make 1 contain -2 and 4 contain 1. This
would yield:
0
|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
-3
|
-2
|
0
|
0
|
1
|
-1
|
-1
|
-1
|
-1
|
Then Union(2,4) would cause Find(2) to be 0 and Find(4) to be 1 so we
would union 0 and 1. Since 0 contains the more negative number (hence a
larger set) we would make 1 point to 0 and 0 would contain -3+-2=-5,
the total number of elements in the set. This would yield:
0
|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
-5
|
0
|
0
|
0
|
1
|
-1
|
-1
|
-1
|
-1
|
Suppose we skip ahead to the diagram on the previous link that had sets
headed by 0 and 5. This would give us:
0
|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
-5
|
0
|
0
|
0
|
1
|
-4
|
5
|
8
|
5
|
Now when we do a Union(4,7), the Find(4) goes from 4 to 1 to 0. We
repeat that path and make 4 and 1 both point to 0. Thus, so far,
we have modified the 0 set to:
0
|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
-5
|
0
|
0
|
0
|
0
|
-4
|
5
|
8
|
5
|
Similarly the Find(7) goes from 7 to 8 to 5. we repeat that path
and make 7 and 8 both point to 5. This yields:
0
|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
-5
|
0
|
0
|
0
|
0
|
-4
|
5
|
5
|
5
|
and, finally, when we complete the Union(4,7) we see that wee will
union 0 (what Find(4) gave us) and 5 (what Find(7) gave us) and since 0
is more negative, we make the value in 0 -5+-4=-9 and the value in 5 0
to give us:
0
|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
-9
|
0
|
0
|
0
|
0
|
0
|
5
|
5
|
5
|
This is the Union-Find algorithm.