- A more agressive approach to minimizing the heights of the component trees is path compression.
- This almost makes all heights be 0 or 1.
4 (height 0) 8 (height 1) /|\ 3 9 5
- Make pcomp be the child of qcomp, but then make every site in the path from p to pcomp be a child of qcomp.
For example, with components:
0 1 5 | | | +---+ +---+ +---+ | | | | | | 2 6 3 4 7 8 | 9
excute union(9,8)
Then
1. p = 9 and q = 8 2. pcomp = 0 and qcomp = 5 3. make 0 be a child of 5 4. make sites p to pcomp be a children of qcomp: make 9 and 6 be children of 5
So first (after step 3) of union(9,8) we get
0 1 5 1 5 | | | | | +---+ +---+ +---+ => +---+ +---+---+ | | | | | | | | | | | 2 6 3 4 7 8 3 4 0 7 8 | | 9 +---+ | | 2 6 | 9
Then after path compression,
1 5 | | => +---+ +-+-+-+-+ | | | | | | | 3 4 0 9 6 7 8 | 2
After this compression, the loop in find(p) will execute only once for p = 0, 6, 9 as well as 7 and 8.