summaryrefslogtreecommitdiff
path: root/java/qfind/QuickUnionUF.java
diff options
context:
space:
mode:
authorCarlos Maiolino <[email protected]>2025-07-10 22:55:07 +0200
committerCarlos Maiolino <[email protected]>2025-07-10 22:56:55 +0200
commitd98f46ce647846b0aa30b2e16a30fd4e152a1bf5 (patch)
tree267474fcc77cf20b428f6f4c7f768ca09f4cfe0e /java/qfind/QuickUnionUF.java
parent869e68986aa8f69af6e7842260a68d1e5c6f796f (diff)
Add new code
Signed-off-by: Carlos Maiolino <[email protected]>
Diffstat (limited to 'java/qfind/QuickUnionUF.java')
-rw-r--r--java/qfind/QuickUnionUF.java47
1 files changed, 47 insertions, 0 deletions
diff --git a/java/qfind/QuickUnionUF.java b/java/qfind/QuickUnionUF.java
new file mode 100644
index 0000000..aab4fb4
--- /dev/null
+++ b/java/qfind/QuickUnionUF.java
@@ -0,0 +1,47 @@
+/*
+ * Quick Union algorithm
+ *
+ * Slightly better than quickfind
+ *
+ * treats each element in the array as a node in a tree and trees may be
+ * connected together or not. Essentially each element might be its own tree.
+ *
+ * Find: Check if p and q have the same root
+ *
+ * Union. Merge components containing p and q, set the id of p's root to the id
+ * of q's root.
+ *
+ * Still too slow though. Trees can get too tall, where the worst case is a tree
+ * where one element points to a single one until the end of the tree,
+ * essentially creating an array.
+ */
+
+public class QuickUnionUF {
+ private int[] id;
+
+ /* Constructor */
+ public QuickUnionUF(int N) {
+ id = new int[N];
+
+ for (int i = 0; i < N; i++)
+ id[i] = i;
+ }
+
+ /* Return root of 'i' */
+ private int root(int i) {
+ while (i != id[i])
+ i = id[i];
+ return i;
+ }
+
+ /* Are the objects connected */
+ public boolean connected(int p, int q) {
+ return root(p) == root(q);
+ }
+
+ /* Connect two objects */
+ public void union(int p, int q) {
+ int proot = root(p);
+ id[proot] = root(q);
+ }
+}