Skip to content
This repository has been archived by the owner on Oct 22, 2021. It is now read-only.

feat: add Disjoint Set Data Structure using Java #125

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions Data Structures/DisjointSet/DisjointSet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
public class DisjointSet {
private int[] parent;

public DisjointSet(int n) {
parent = new int[n];
for (var i = 0; i < n; i++) {
parent[i] = i;
}
}

public int find(int x) {
if (x == parent[x]) {
return x;
}
// compress the paths
return parent[x] = find(parent[x]);
}

public void union(int x, int y) {
var px = find(x);
var py = find(y);
if (px != py) {
parent[px] = py;
}
}
// number of groups
public int size() {
int ans = 0;
for (int i = 0; i < parent.length; ++ i) {
if (i == parent[i]) ans ++;
}
return ans;
}

public static void main(String[] args) {
var ds = new DisjointSet(5);
System.out.println(ds.find(3));

ds.union(3, 4);
System.out.println(ds.find(3)); // after join, 3's parent is 4.
}
}