Skip to content

Commit b608657

Browse files
authored
Add Disjoint Set (TheAlgorithms#2684)
1 parent 4a05e3e commit b608657

2 files changed

Lines changed: 43 additions & 0 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package DataStructures.DisjointSets;
2+
3+
public class DisjointSets<T> {
4+
public Node<T> MakeSet(T x) {
5+
return new Node<T>(x);
6+
};
7+
8+
public Node<T> FindSet(Node<T> node) {
9+
if (node != node.parent) {
10+
node.parent = FindSet(node.parent);
11+
}
12+
13+
return node.parent;
14+
}
15+
16+
public void UnionSet(Node<T> x, Node<T> y) {
17+
Node<T> nx = FindSet(x);
18+
Node<T> ny = FindSet(y);
19+
20+
if (nx == ny) {
21+
return;
22+
}
23+
if (nx.rank > ny.rank) {
24+
ny.parent = nx;
25+
} else if (ny.rank > nx.rank) {
26+
nx.parent = ny;
27+
} else {
28+
nx.parent = ny;
29+
ny.rank++;
30+
}
31+
}
32+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package DataStructures.DisjointSets;
2+
3+
public class Node<T> {
4+
public int rank;
5+
public Node<T> parent;
6+
public T data;
7+
public Node(T data) {
8+
this.data = data;
9+
parent = this;
10+
}
11+
}

0 commit comments

Comments
 (0)