Union Find With Path Compression (Rust)
Implement a Rust disjoint set union find with path compression and union by rank for near constant amortized time.
Code
struct UnionFind { parent: Vec<usize>, rank: Vec<usize>, count: usize }
impl UnionFind {
fn new(n: usize) -> Self { Self { parent: (0..n).collect(), rank: vec![0; n], count: n } }
fn find(&mut self, mut x: usize) -> usize { while self.parent[x] != x { self.parent[x] = self.parent[self.parent[x]]; x = self.parent[x]; } x }
fn union(&mut self, a: usize, b: usize) -> bool {
let (ra, rb) = (self.find(a), self.find(b));
if ra == rb { return false; }
if self.rank[ra] < self.rank[rb] { self.parent[ra] = rb; } else if self.rank[ra] > self.rank[rb] { self.parent[rb] = ra; } else { self.parent[rb] = ra; self.rank[ra] += 1; }
self.count -= 1; true
}
}How the snippet works
Union Find With Path Compression (Rust) is built around the functions new, find and union.
Applying it
The main signature reads fn new(n: usize) -> Self
Import new from the file and call it — the rest of the code is implementation detail.
Statements that matter
fn new(n: usize) -> Self { Self { parent: (0..n).collect(), rank: vec![0; n], count: n } }
if ra == rb { return false; }
Interactive Tools for This Topic
JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SVG Path VisualizerParse SVG path d attributes (M/L/H/V/C/S/Q/T/A/Z), render a scaled wireframe preview with vertices and control handles, and compute bounding boxes.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `new`, `find`, `union` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.