Loading course index…

Course navigation & on this page
Union–find · Course example

UnionFind

Original UnionFind implementation from the supplied Java collection.

Java14 source linescode/UnionFind.java

Overview

This file is preserved as a supporting course example. Its declarations, methods and comments below are the authoritative description of its behavior.

This reference entry presents original author documentation and source. It is supplementary material, not an additional numbered lecture.

Original course code

Source: code/UnionFind.java. Original logic, comments, variable names and attribution are retained.

Download UnionFind.java
UnionFind.javaJAVA
public static void main(String[] args){   int N = StdIn.readInt();   UF uf = new UF(N);   while (!StdIn.isEmpty())   {      int p = StdIn.readInt();      int q = StdIn.readInt();      if (!uf.connected(p, q))      {         uf.union(p, q);         StdOut.println(p + " " + q);      }} }