From b608657e504294fcca241d3baad99b9c39b868c6 Mon Sep 17 00:00:00 2001 From: NimrodRak <68863114+NimrodRak@users.noreply.github.com> Date: Sun, 24 Oct 2021 10:28:21 +0300 Subject: [PATCH] Add Disjoint Set (#2684) --- DataStructures/DisjointSets/DisjointSets.java | 32 +++++++++++++++++++ DataStructures/DisjointSets/Node.java | 11 +++++++ 2 files changed, 43 insertions(+) create mode 100644 DataStructures/DisjointSets/DisjointSets.java create mode 100644 DataStructures/DisjointSets/Node.java diff --git a/DataStructures/DisjointSets/DisjointSets.java b/DataStructures/DisjointSets/DisjointSets.java new file mode 100644 index 000000000..d4d462803 --- /dev/null +++ b/DataStructures/DisjointSets/DisjointSets.java @@ -0,0 +1,32 @@ +package DataStructures.DisjointSets; + +public class DisjointSets { + public Node MakeSet(T x) { + return new Node(x); + }; + + public Node FindSet(Node node) { + if (node != node.parent) { + node.parent = FindSet(node.parent); + } + + return node.parent; + } + + public void UnionSet(Node x, Node y) { + Node nx = FindSet(x); + Node ny = FindSet(y); + + if (nx == ny) { + return; + } + if (nx.rank > ny.rank) { + ny.parent = nx; + } else if (ny.rank > nx.rank) { + nx.parent = ny; + } else { + nx.parent = ny; + ny.rank++; + } + } +} \ No newline at end of file diff --git a/DataStructures/DisjointSets/Node.java b/DataStructures/DisjointSets/Node.java new file mode 100644 index 000000000..8e6bb6547 --- /dev/null +++ b/DataStructures/DisjointSets/Node.java @@ -0,0 +1,11 @@ +package DataStructures.DisjointSets; + +public class Node { + public int rank; + public Node parent; + public T data; + public Node(T data) { + this.data = data; + parent = this; + } +}