This is the code of the simple lookup, suitable for the case of small amount of data:
int findx (int x)
{
int r=x;
while (Parent[r]!=r)
R=PARENT[R];
return R;
}
Here's how to find the element using path compression:
int find (int x) //Find the collection where the X element resides, and compress the path when backtracking
{
if (x! = Parent[x])
{
PARENT[X] = find (parent[x]); The compression path when backtracking
} //The nodes that pass from the X-node search to the ancestor node point to the Ancestor node.
return parent[x];
}
The above is a recursive way to compress the path, but the recursive compression path may cause overflow stack, I used to because of this re n times, below we say a non-recursive way to do the path compression:
int find (int x)
{
int K, j, R;
R = x;
while (r! = Parent[r]) //Lookup and Node
r = parent[r]; Find the node and use R to record
k = x;
while (k! = r) //non-recursive path compression operation
{
j = Parent[k]; The parent node of the J staging Parent[k]
Parent[k] = r; PARENT[X] Point and Node
K = J; K Move to parent node
}
return R; Returns the value of the root node
}
(turn) and set path compression