MAKE-SET(x)
x.p = x
x.rank = 0
UNION(x, y)
LINK(FIND-SET(x),FIND-SET(y))
LINK(x, y)
if x.rank > y.rank
y.p = x
else
x.p = y
if x.rand == y.rank
y.rank = y.rank +1
The FIND-SET procedure with path compression is quite simple:
FIND-SET(x)
if x != x.p
x.p = FIND-SET(x.p)
return x.p
You can find the pseudocode in Introduction to Algorithms 3rd at chapter 21.
this is the pseudocode for disjoint-set forests with rank and path compression. From the pseudocode, we can see that each time before union operation, we will first find the set number of each node. In the FIND-SET operation with path compression, the height of x and y will always become only 2. Because x.p and y.p will both point to the set's root after FIND-SET. Why union by rank still needed ?
Shihab Shahriar have solved my problem, his answer is really impressive!