Professional Documents
Culture Documents
CS301 Lec36
CS301 Lec36
Data Structures
1 2 3 4 5 6 7 8
-1 -1 -1 -1 -1 -1 -1 -1
1 2 3 4 5 6 7 8
Eight elements, initially in different sets.
Union by Size
1 2 3 4 5 7 8
-1 -1 -1 -2 -1 4 -1 -1
1 2 3 4 5 6 7 8
Union(4,6)
Union by Size
1 2 4 5 7 8
3 6
-1 -2 2 -2 -1 4 -1 -1
1 2 3 4 5 6 7 8
Union(2,3)
Union by Size
2 4 5 7 8
3 1 6
4 -2 2 -3 -1 4 -1 -1
1 2 3 4 5 6 7 8
Union(1,4)
Union by Size
4 5 7 8
2 1 6
4 4 2 -5 -1 4 -1 -1
1 2 3 4 5 6 7 8
Union(2,4)
Union by Size
4 7 8
2 1 6 5
4 4 2 -6 4 4 -1 -1
1 2 3 4 5 6 7 8
Union(5,4)
Analysis of Union by Size
Intuitive Proof:
Initially, every element is at depth zero.
When its depth increases as a result of a
union operation (it’s in the smaller tree), it is
placed in a tree that becomes at least twice
as large as before (union of two equal size
trees).
How often can each union be done? -- log2n
times, because after at most log2n unions,
the tree will contain all n elements.
Union by Height
find (i)
{
if (parent[i] < 0)
return i;
else
return parent[i] = find(parent[i]);
}
Path Compression
Find(1) 7
13
8 3 22 6
4 5
9
31 32 11 30 10
2
35
20 16 14 12
1 13
17 18 19
Path Compression
Find(1) 7
13
8 3 22 6
4 5
9
31 32 11 30 10
2
35
20 16 14 12
1 13
17 18 19
Path Compression
Find(1) 7
13
8 3 22 6
4 5
9
31 32 11 30 10
2
35
20 16 14 12
1 13
17 18 19
Path Compression
Find(1) 7
13
8 3 22 6
4 5
9
31 32 11 30 10
2
35
20 16 14 12
1 13
17 18 19
Path Compression
Find(1) 7
13
8 3 22 6
4 5
9
31 32 11 30 10
2
35
20 16 14 12
1 13
17 18 19
Path Compression
Find(a)
e
a
Path Compression
Find(a) f
a b c d e
Timing with Optimization