s LearnSqueak.com

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.

9 native experiments10 SUnit testsUnion by size

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.

  1. Use a copy of a Squeak 6.1 image with matching changes and sources files.
  2. 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.
  3. 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.

  1. File in union-find.st through the Squeak File List before running the launcher.
  2. Use the same Workspace for every experiment so view keeps referring to this window.
  3. The coloured groups are calculated from the model; colours and root numbers have no meaning outside this demonstration.
LSDisjointSet method · read in Browser
initialize
 super initialize.
 parents := (1 to: 8) asArray.
 sizes := Array new: 8 withAll: 1.
 count := 8
Same Workspace · Do it
view := LSUnionView open.

Expected: Eight singleton components appear, with parent array #(1 2 3 4 5 6 7 8).

NATIVE SQUEAK CAPTURE
Native union-find lab after experiment 1: Start with eight separate sets
Genuine Squeak Morphic window after experiment 1; parent pointers and component membership come from the live model.

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.

  1. Read the whole union method in the Browser rather than pasting this method definition into a Workspace.
  2. Both input indices are validated before any find operation can compress a path.
  3. When sizes tie, this implementation keeps the first root. Choosing the other root would describe the same partition.
LSDisjointSet method · read in Browser
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.
 ^ true
Same Workspace · Do it
view nextUnion.

Expected: Item 2 now points to 1. There are seven components.

NATIVE SQUEAK CAPTURE
Native union-find lab after experiment 2: Join two items
Genuine Squeak Morphic window after experiment 2; parent pointers and component membership come from the live model.

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.

  1. Compare item 4’s parent with item 3’s parent: both chains lead to root 3.
  2. The loop terminates because the union operation only attaches one root below another root.
  3. Arbitrary edits to the internal parent array could create a cycle; the public accessor returns a copy to prevent that.
LSDisjointSet method · read in Browser
rootOf: item
 | current |
 self check: item.
 current := item.
 [current = (parents at: current)] whileFalse: [current := parents at: current].
 ^ current
Same Workspace · Do it
view nextUnion.

Expected: The pair 3 and 4 is joined. Roots 1 and 3 each represent two members; six components remain.

NATIVE SQUEAK CAPTURE
Native union-find lab after experiment 3: Find a representative without changing it
Genuine Squeak Morphic window after experiment 3; parent pointers and component membership come from the live model.

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.

  1. Do not confuse an immediate parent with the component representative.
  2. connected:to: compares representatives and may compress paths because it uses find:.
  3. The pictured state is before extra queries. Running an additional find: may change pointers without changing membership.
LSDisjointSet method · read in Browser
connected: first to: second
 self check: first. self check: second.
 ^ (self find: first) = (self find: second)
Same Workspace · Do it
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.

NATIVE SQUEAK CAPTURE
Native union-find lab after experiment 4: Merge components transitively
Genuine Squeak Morphic window after experiment 4; parent pointers and component membership come from the live model.

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.

  1. sizeOf: accepts any member and finds its representative before reading the size.
  2. Old size entries at non-roots are intentionally not updated or used to choose attachments.
  3. 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.
LSDisjointSet method · read in Browser
sizeOf: item
 ^ sizes at: (self find: item)
Same Workspace · Do it
view nextUnion.

Expected: 5 and 6 merge, leaving four components. The 1–4 component still has four members.

NATIVE SQUEAK CAPTURE
Native union-find lab after experiment 5: Track component sizes at roots
Genuine Squeak Morphic window after experiment 5; parent pointers and component membership come from the live model.

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.

  1. The parent accessor copies the Array, so modifying its result does not mutate the model.
  2. This is incremental undirected connectivity. It does not record direction, edge weights, or paths between items.
  3. It cannot split a component when an edge is deleted. That would need a different algorithm or a rebuild from saved edges.
LSDisjointSet method · read in Browser
parents
 ^ parents copy
Same Workspace · Do it
view nextUnion.

Expected: Three components remain: {1,2,3,4}, {5,6}, and {7,8}.

NATIVE SQUEAK CAPTURE
Native union-find lab after experiment 6: Keep unrelated groups separate
Genuine Squeak Morphic window after experiment 6; parent pointers and component membership come from the live model.

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.

  1. This model deliberately accepts only integer IDs 1 through 8. It is a bounded teaching model, not a generic container.
  2. check: rejects text, fractions and out-of-range indices before array access.
  3. For a larger application, initialize arrays to n items, add a label-to-index mapping, and test the boundary cases again.
LSDisjointSet method · read in Browser
check: item
 (item isInteger and: [item between: 1 and: parents size])
  ifFalse: [self error: 'Use an integer from 1 through 8']
Same Workspace · Do it
view nextUnion.

Expected: Two four-member components remain. Parents are #(1 1 1 3 5 5 5 7).

NATIVE SQUEAK CAPTURE
Native union-find lab after experiment 7: Use sizes rather than numeric labels
Genuine Squeak Morphic window after experiment 7; parent pointers and component membership come from the live model.

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.

  1. find: first discovers the root, then walks the original path again.
  2. Save next before replacing a parent. Otherwise the old path is lost and the walk can end too early.
  3. An already-connected union answers false and does not decrement count, although its finds may still shorten paths.
LSDisjointSet method · read in Browser
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].
 ^ root
Same Workspace · Do it
view nextUnion.

Expected: One component remains, with all eight items. Some parent pointers still take more than one hop to reach 1.

NATIVE SQUEAK CAPTURE
Native union-find lab after experiment 8: Connect the final two components
Genuine Squeak Morphic window after experiment 8; parent pointers and component membership come from the live model.

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.

  1. The GIF is a sequence of genuine native window captures after scripted operations, not a mouse recording or an animation of every pointer assignment.
  2. 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.
  3. 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.
LSDisjointSet method · read in Browser
count
 ^ count
Same Workspace · Do it
view compress.

Expected: The parent array is #(1 1 1 1 1 1 1 1), still with one eight-member component.

NATIVE SQUEAK CAPTURE
Native union-find lab after experiment 9: Compress paths without merging anything
Genuine Squeak Morphic window after experiment 9; parent pointers and component membership come from the live model.

Watch the native sequence

NATIVE SQUEAK CAPTURE
Eight singleton components before the union sequence
Nine native window states, captured after the exact commands in this lesson.

Test the model and try an extension

After filing in union-find-tests.st · Print it
LSDisjointSetTest suite run

Expected: 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