-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDisjSets.cpp
More file actions
44 lines (39 loc) · 824 Bytes
/
Copy pathDisjSets.cpp
File metadata and controls
44 lines (39 loc) · 824 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include "DisjSets.h"
/**
* Construct the disjoint sets object.
*/
DisjSets::DisjSets( int numElements ) : s( numElements, -1 )
{
}
/**
* Union two disjoint sets.
* For simplicity, we assume root1 and root2 are distinct
* and represent set names.
* root1 is the root of set 1.
* root2 is the root of set 2.
*/
void DisjSets::unionSets(int root1, int root2) {
if (s[root1] < s[root2]) {
s[root1] += s[root2]; //update size of root1 tree
s[root2] = root1; // Make root1 new root
}
else
{
s[root2] += s[root1]; //update size of root 2
s[root1] = root2; // make root2 new root
}
}
/**
* Perform a find with path halving per exercise 8.16a from the book.
*/
int DisjSets::find( int x )
{
if (s[x] < 0)
{
return x;
}
else
{
return s[x] = find(s[x]);
}
}