DISJOINT SETS · CONNECTIVITY
Union-find: connect components
Build a native Squeak union-find lab with weighted unions, path compression, parent-pointer views and tested connectivity experiments.
Install the native lab
Explore disjoint sets, also called union-find, by watching eight numbered items become connected. Install the complete application, then read and run the experiments in order. This is a source-guided workshop, not nine independent snippets.
- Use a copy of a Squeak 6.1 image with matching changes and sources files.
- Download union-find.st. Select it in Squeak’s File List and choose fileIn. Do not paste the whole chunk-format file into a Workspace.
- Open a Workspace and keep it open for all nine experiments. Method definitions shown below belong in the Browser; only the labelled Workspace commands should be evaluated.
Prerequisites: classes, arrays and collections, and loops and blocks.
SUnit tests · Complete lab kit
Native Squeak only: this app is not installed in the SqueakJS playground. It uses no network, timers or persistent storage. Keep the fixed-layout window at least 980 × 620 pixels.
01 · Start with eight separate sets
Each item begins as its own parent. A root is an item whose parent is itself. Two items belong to the same component exactly when their parent chains end at the same root. The model stores parent pointers, not the original graph edges.
- File in union-find.st through the Squeak File List before running the launcher.
- Use the same Workspace for every experiment so view keeps referring to this window.
- The coloured groups are calculated from the model; colours and root numbers have no meaning outside this demonstration.
initialize
super initialize.
parents := (1 to: 8) asArray.
sizes := Array new: 8 withAll: 1.
count := 8view := LSUnionView open.Expected: Eight singleton components appear, with parent array #(1 2 3 4 5 6 7 8).

02 · Join two items
union:with: merges components, not merely the two named items. The first pair in the fixed demonstration is 1 and 2. A successful merge reduces the component count by one.
- Read the whole union method in the Browser rather than pasting this method definition into a Workspace.
- Both input indices are validated before any find operation can compress a path.
- When sizes tie, this implementation keeps the first root. Choosing the other root would describe the same partition.
union: first with: second
| a b temporary |
self check: first. self check: second.
a := self find: first. b := self find: second.
a = b ifTrue: [^ false].
(sizes at: a) < (sizes at: b) ifTrue: [temporary := a. a := b. b := temporary].
parents at: b put: a.
sizes at: a put: (sizes at: a) + (sizes at: b).
count := count - 1.
^ trueview nextUnion.Expected: Item 2 now points to 1. There are seven components.

03 · Find a representative without changing it
rootOf: follows parents until it encounters a self-parent. This read-only helper is also used for drawing so simply repainting the view does not secretly compress paths.
- Compare item 4’s parent with item 3’s parent: both chains lead to root 3.
- The loop terminates because the union operation only attaches one root below another root.
- Arbitrary edits to the internal parent array could create a cycle; the public accessor returns a copy to prevent that.
rootOf: item
| current |
self check: item.
current := item.
[current = (parents at: current)] whileFalse: [current := parents at: current].
^ currentview nextUnion.Expected: The pair 3 and 4 is joined. Roots 1 and 3 each represent two members; six components remain.

04 · Merge components transitively
The next request joins 2 and 4. Their representatives are 1 and 3, so the roots are joined. All of 1, 2, 3 and 4 now belong together even though no request directly joined 1 with 4.
- Do not confuse an immediate parent with the component representative.
- connected:to: compares representatives and may compress paths because it uses find:.
- The pictured state is before extra queries. Running an additional find: may change pointers without changing membership.
connected: first to: second
self check: first. self check: second.
^ (self find: first) = (self find: second)view nextUnion.Expected: Five components remain. The raw parents are #(1 1 1 3 5 6 7 8): item 4 still reaches root 1 through 3.

05 · Track component sizes at roots
The size array supports weighted union: attach the smaller component root below the larger one. Only size entries at current roots are meaningful. The count variable is the number of components, not the number of items.
- sizeOf: accepts any member and finds its representative before reading the size.
- Old size entries at non-roots are intentionally not updated or used to choose attachments.
- Weighting limits uncompressed tree depth to O(log n) because an item’s tree can grow deeper only when its component size at least doubles.
sizeOf: item
^ sizes at: (self find: item)view nextUnion.Expected: 5 and 6 merge, leaving four components. The 1–4 component still has four members.

06 · Keep unrelated groups separate
A disjoint-set structure answers connectivity efficiently while new connections are added. Here the pair 7 and 8 forms another two-item group; it does not affect either existing group.
- The parent accessor copies the Array, so modifying its result does not mutate the model.
- This is incremental undirected connectivity. It does not record direction, edge weights, or paths between items.
- It cannot split a component when an edge is deleted. That would need a different algorithm or a rebuild from saved edges.
parents
^ parents copyview nextUnion.Expected: Three components remain: {1,2,3,4}, {5,6}, and {7,8}.

07 · Use sizes rather than numeric labels
The next union joins 6 and 8, whose roots are 5 and 7. Their sizes tie, so root 5 is retained. A representative is not necessarily the smallest item in a general union-find implementation.
- This model deliberately accepts only integer IDs 1 through 8. It is a bounded teaching model, not a generic container.
- check: rejects text, fractions and out-of-range indices before array access.
- For a larger application, initialize arrays to n items, add a label-to-index mapping, and test the boundary cases again.
check: item
(item isInteger and: [item between: 1 and: parents size])
ifFalse: [self error: 'Use an integer from 1 through 8']view nextUnion.Expected: Two four-member components remain. Parents are #(1 1 1 3 5 5 5 7).

08 · Connect the final two components
Joining 4 and 8 first finds their roots, compressing the paths used by those two queries. Then the two equal-size trees are combined. The component partition changes only once.
- find: first discovers the root, then walks the original path again.
- Save next before replacing a parent. Otherwise the old path is lost and the walk can end too early.
- An already-connected union answers false and does not decrement count, although its finds may still shorten paths.
find: item
| root current next |
root := self rootOf: item.
current := item.
[current = root] whileFalse: [
next := parents at: current.
parents at: current put: root.
current := next].
^ rootview nextUnion.Expected: One component remains, with all eight items. Some parent pointers still take more than one hop to reach 1.

09 · Compress paths without merging anything
Path compression rewrites each visited item’s parent to its representative. The Compress all paths button calls find: on every item, so all eight parents become 1. Connectivity and component sizes stay unchanged.
- The GIF is a sequence of genuine native window captures after scripted operations, not a mouse recording or an animation of every pointer assignment.
- Union by size plus path compression has near-constant amortized cost across sequences of operations, commonly written O(alpha(n)); that is not a strict constant-time guarantee for every call.
- The read-only rootOf: helper used for drawing does not compress. Drawing scans all members once per component and can dominate model operation cost. This teaching view is bounded to eight items.
count
^ countview compress.Expected: The parent array is #(1 1 1 1 1 1 1 1), still with one eight-member component.

Watch the native sequence

Test the model and try an extension
LSDisjointSetTest suite runExpected: 10 tests, 10 passes, no failures or errors. Tests cover singleton initialization, successful and redundant merges, transitive connectivity, path compression, weighted union, invalid indices/types, defensive copying and the complete seven-union sequence.
Try Reset, repeat the sequence, and query view sets connected: 1 to: 8 with Print it before and after the last merge. Queries may shorten paths but never change component membership. To see those pointer changes, run view changed afterward.
Next challenge: accept a configurable number of items, then add a label mapping for a small network. Keep graph edges separately if you need to show actual paths or rebuild after deletion. This demonstration has no edge storage, deletion, persistence, concurrency control, or general-purpose label interface.
Learn SUnit · Compare pathfinding · Official Squeak documentation