s LearnSqueak.com

SMALLTALK LAB

Kruskal minimum spanning tree: connect a network cheaply

Build Kruskal’s algorithm in Squeak, trace component merges and rejected cycles, handle disconnected graphs and negative costs, and check a tiny minimum tree by exhaustive enumeration.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Use native Squeak 6.1 and a Workspace. Select each complete expression and choose Print it. Every checkpoint is independent: no installed methods or earlier Workspace variables are needed. Declare n vertices numbered 1 through n, including isolated vertices. An edge is #(u v weight), with valid integer endpoints and comparable finite numeric weights. Store undirected edges with u <= v; the snippets assume this contract rather than implementing an input parser. No directed graphs or real-world routing data are used.

These are native Squeak 6.1 examples. Each checkpoint is independent: open the download as text, copy one complete expression into Workspace and choose Print it. Do not file in the checkpoint collection as a class definition.

01 - Model a network, not a route

Vertices 1 through 4 are A through D. Each triple stores two endpoints and one cost. Edges are undirected: store each once, with the smaller endpoint first. A spanning tree connects every vertex using three edges; its objective is total installed cost, not distance from a starting vertex.

Independent Workspace expression - select all, then Print it
| names edges |
names := #(A B C D).
edges := #(#(1 4 9) #(2 4 6) #(1 3 3) #(3 4 4) #(2 3 2) #(1 2 1)).
{edges size. names at: edges last first.
 names at: edges last second. edges last third}

Expected: #(6 A B 1)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Model a network, not a route
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Replace the final edge weight with 7. Only the reported cost changes; endpoint positions still identify A and B.

Download this checkpoint

02 - Sort by cost with deterministic tie breaking

Kruskal examines cheapest edges first. The comparator orders equal costs by first endpoint, then second endpoint. This makes the chosen answer reproducible when several minimum trees exist. Non-strict <= in the final comparison also handles identical triples.

Independent Workspace expression - select all, then Print it
| edges sorted |
edges := #(#(1 4 9) #(2 4 6) #(1 3 3) #(3 4 4) #(2 3 2) #(1 2 1)).
sorted := edges asSortedCollection: [:a :b |
 a third = b third
  ifTrue: [a first = b first
   ifTrue: [a second <= b second] ifFalse: [a first < b first]]
  ifFalse: [a third < b third]].
sorted asArray

Expected: #(#(1 2 1) #(2 3 2) #(1 3 3) #(3 4 4) #(2 4 6) #(1 4 9))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Sort by cost with deterministic tie breaking
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Give edge 1–3 cost 2. It now comes before edge 2–3 because its first endpoint is smaller.

Download this checkpoint

03 - Merge components by relabeling

Initially every vertex is its own connected component. Accepting A–B replaces every occurrence of B’s old component label with A’s label. The labels are identifiers, not distances or parent pointers. Equal labels mean a path already exists through accepted edges.

Independent Workspace expression - select all, then Print it
| labels left right |
labels := (1 to: 4) asArray.
left := labels at: 1. right := labels at: 2.
1 to: labels size do: [:vertex |
 (labels at: vertex) = right ifTrue: [labels at: vertex put: left]].
{labels. labels asSet size. (labels at: 1) = (labels at: 2)}

Expected: #(#(1 1 3 4) 3 true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Merge components by relabeling
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Repeat the merge for vertices 2 and 3 using their current labels. The resulting labels are #(1 1 1 4), even though the edge starts at vertex 2.

Download this checkpoint

04 - Reject the first cycle

After A–B and B–C, A and C already share a component. Adding A–C would close a cycle. Rejection leaves the selected edges, labels and total unchanged; the next useful edge can still connect D.

Independent Workspace expression - select all, then Print it
| labels chosen total edge accepted |
labels := #(1 1 1 4) copy.
chosen := #(#(1 2 1) #(2 3 2)) asOrderedCollection.
total := 3. edge := #(1 3 3).
accepted := (labels at: edge first) ~= (labels at: edge second).
accepted ifTrue: [chosen add: edge. total := total + edge third].
{accepted. chosen asArray. total. labels asSet size}

Expected: #(false #(#(1 2 1) #(2 3 2)) 3 2)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Reject the first cycle
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try edge #(3 4 4). The test becomes true, but this deliberately limited snippet does not merge labels. The complete algorithm in the next step performs both operations together.

Download this checkpoint

05 - Build the complete minimum spanning tree

This independently runnable block sorts input, tests components, accepts safe edges and merges their labels. It returns {selected edges. total cost. component count}. The sample finishes with one component, three selected edges and cost 7. Scanning the remaining edges is harmless: their endpoints are already connected.

Independent Workspace expression - select all, then Print it
| forest |
forest := [:count :input | | labels chosen sorted total |
 labels := (1 to: count) asArray.
 chosen := OrderedCollection new. total := 0.
 sorted := input asSortedCollection: [:a :b |
  a third = b third
   ifTrue: [a first = b first
    ifTrue: [a second <= b second] ifFalse: [a first < b first]]
   ifFalse: [a third < b third]].
 sorted do: [:edge | | left right |
  left := labels at: edge first. right := labels at: edge second.
  left = right ifFalse: [
   chosen add: edge. total := total + edge third.
   1 to: count do: [:vertex |
    (labels at: vertex) = right ifTrue: [labels at: vertex put: left]]]].
 {chosen asArray. total. labels asSet size}].
forest value: 4 value: #(#(1 4 9) #(2 4 6) #(1 3 3) #(3 4 4) #(2 3 2) #(1 2 1))

Expected: #(#(#(1 2 1) #(2 3 2) #(3 4 4)) 7 1)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Build the complete minimum spanning tree
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Change the expensive A–D edge from 9 to 0. The new minimum tree uses A–D, A–B and B–C, with total 3.

Download this checkpoint

06 - Return a forest when the input is disconnected

An isolated vertex is still a component even if it never appears in an edge. With five declared vertices and only A–B and C–D, no spanning tree exists. Kruskal returns a minimum spanning forest, one minimum tree per connected component. The same block accepts empty and singleton graphs.

Independent Workspace expression - select all, then Print it
| forest |
forest := [:count :input | | labels chosen sorted total |
 labels := (1 to: count) asArray.
 chosen := OrderedCollection new. total := 0.
 sorted := input asSortedCollection: [:a :b |
  a third = b third
   ifTrue: [a first = b first
    ifTrue: [a second <= b second] ifFalse: [a first < b first]]
   ifFalse: [a third < b third]].
 sorted do: [:edge | | left right |
  left := labels at: edge first. right := labels at: edge second.
  left = right ifFalse: [
   chosen add: edge. total := total + edge third.
   1 to: count do: [:vertex |
    (labels at: vertex) = right ifTrue: [labels at: vertex put: left]]]].
 {chosen asArray. total. labels asSet size}].
{forest value: 5 value: #(#(3 4 4) #(1 2 1)).
 forest value: 0 value: #(). forest value: 1 value: #()}

Expected: #(#(#(#(1 2 1) #(3 4 4)) 5 3) #(#() 0 0) #(#() 0 1))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Return a forest when the input is disconnected
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: For every returned forest, verify selected edge count = declared vertex count minus component count. Zero vertices returns zero components; do not call it a connected tree.

Download this checkpoint

07 - Allow negative costs and equal-weight choices

Unlike the usual Dijkstra algorithm, Kruskal needs no nonnegative-weight restriction. A negative edge is just examined early. Self-loops are always rejected because both endpoints have the same label. In this triangle, two distinct trees tie at total -1; the endpoint tie break chooses one consistently.

Independent Workspace expression - select all, then Print it
| forest |
forest := [:count :input | | labels chosen sorted total |
 labels := (1 to: count) asArray.
 chosen := OrderedCollection new. total := 0.
 sorted := input asSortedCollection: [:a :b |
  a third = b third
   ifTrue: [a first = b first
    ifTrue: [a second <= b second] ifFalse: [a first < b first]]
   ifFalse: [a third < b third]].
 sorted do: [:edge | | left right |
  left := labels at: edge first. right := labels at: edge second.
  left = right ifFalse: [
   chosen add: edge. total := total + edge third.
   1 to: count do: [:vertex |
    (labels at: vertex) = right ifTrue: [labels at: vertex put: left]]]].
 {chosen asArray. total. labels asSet size}].
forest value: 3 value: #(#(2 3 1) #(1 3 1) #(1 2 -2) #(2 2 -9))

Expected: #(#(#(1 2 -2) #(1 3 1)) -1 1)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Allow negative costs and equal-weight choices
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Remove the self-loop: the result is unchanged. Reverse the input order: the result is also unchanged. Equal minimum cost does not imply a unique tree.

Download this checkpoint

08 - Check optimality with an independent tiny oracle

For three vertices, enumerate all two-edge subsets. Check connectivity by repeatedly growing a reached Set, without component relabeling or sorted-edge selection. A connected two-edge subset on three vertices is a tree. Taking the cheapest of these candidates independently verifies the triangle’s minimum cost. This is exhaustive testing of one fixture, not a replacement for the correctness proof.

Independent Workspace expression - select all, then Print it
| edges costs |
edges := #(#(1 2 1) #(2 3 2) #(1 3 5)).
costs := OrderedCollection new.
1 to: edges size - 1 do: [:i |
 i + 1 to: edges size do: [:j | | pair reached |
  pair := {edges at: i. edges at: j}.
  reached := Set with: 1.
  3 timesRepeat: [pair do: [:edge |
   (reached includes: edge first) ifTrue: [reached add: edge second].
   (reached includes: edge second) ifTrue: [reached add: edge first]]].
  reached size = 3 ifTrue: [
   costs add: (pair inject: 0 into: [:sum :edge | sum + edge third])]]].
{costs asSortedCollection asArray. costs min}

Expected: #(#(3 6 7) 3)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Check optimality with an independent tiny oracle
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Change edge 1–3 to cost -1. The sorted candidate totals become #(0 1 3), and the independent minimum becomes 0. Run the complete Kruskal block on that same triangle to compare.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Kruskal minimum spanning tree: connect a network cheaply native visual trace
Replay of actual Morphic window captures at successive computed stages; not mouse footage.

Download the visual experiment. Select the entire expression and Do it. Change stage := 0. to another supported stage, close the previous window, and run again. The GIF replays those native states. This example needs native Squeak; no new browser playground compatibility is claimed.

Reason about correctness and limits

The invariant is that selected edges form an acyclic forest and labels identify exactly its connected components. An edge between different labels joins two trees without creating a cycle; an edge inside one component would create a cycle. Accepted edges reduce the component count by exactly one.

Why greed is safe: consider the cut separating one endpoint’s current component from the rest. The next accepted edge is a cheapest edge crossing that cut. If a minimum spanning tree extending the current forest omits it, add it and remove an edge crossing the same cut from the resulting cycle. The removed edge costs no less, so some minimum tree still extends the forest. Apply this argument within each input component for disconnected graphs.

A minimum spanning tree minimizes the sum of all chosen edge weights. It does not minimize the route from a chosen start to each vertex. For a triangle with costs A–B = 2, B–C = 2 and A–C = 3, the minimum tree costs 4 but its A-to-C route costs 4 rather than the shortest distance 3.

This teaching implementation uses full component relabeling, not union-find. Sorting costs O(E log E); scanning costs O(E); initialization costs O(V); at most V minus 1 accepted merges each scan V labels. A safe total bound is O(E log E + E + V squared + V), with O(E + V) auxiliary storage including sorted and chosen edges. Union-find with path compression and rank replaces relabeling with near-constant amortized component operations: O(V + E log E + E alpha(V)).

Negative weights do not break the cut argument. Ties can produce multiple minimum trees; deterministic endpoint ordering chooses one, not a more optimal one. A self-loop never helps connect components. Duplicate parallel edges are harmless here, but normalize endpoints if you want a consistent tie order across equivalent input encodings.

Never mutate literal Arrays. The examples allocate labels and collections afresh, and treat input triples as read-only. Endpoints outside 1 through n cause indexing errors. A connected nonempty graph needs V minus 1 accepted edges; a disconnected graph cannot reach that number. Count components rather than silently claiming every result is a spanning tree.

The exhaustive oracle deliberately uses different mechanics from Kruskal. It enumerates all three two-edge choices only for the three-vertex fixture. General enumeration of V minus 1 edges among E edges is combinatorial; do not use it as the production algorithm.

Three practice challenges

Measure decisions rather than just output

Add accepted and rejected counters to the complete algorithm. What should the six-edge four-vertex fixture report? What changes if you stop as soon as one component remains?

Show solution

Increment accepted in the different-label branch and rejected in the equal-label branch. Scanning all six edges reports 3 accepted and 3 rejected: A–C, B–D and A–D are rejected. Stopping once one component remains examines four edges and reports 3 accepted and 1 rejected. The selected tree and total remain unchanged. This early stop applies when the component count is one, not when a disconnected input runs out of useful edges.

Make a minimum tree non-unique

Change A–C from 3 to 2 in the four-vertex fixture. Which tree does the comparator choose, and what other minimum tree exists?

Show solution

The sorted order starts A–B at 1, A–C at 2, B–C at 2, then C–D at 4. Kruskal accepts A–B and A–C, rejects B–C, and accepts C–D for total 7. Replacing A–C with B–C gives a different tree of the same total. The cut argument allows either equal-cost choice.

Recognize a shortest-path counterexample

Use triangle edges #(1 2 2), #(2 3 2), #(1 3 3). What does Kruskal choose? Why would shortest routes from vertex 1 use a different network?

Show solution

Kruskal chooses 1–2 and 2–3 for total 4. The resulting route from 1 to 3 costs 4. A shortest-path tree rooted at 1 uses edges 1–2 and 1–3, giving distances 2 and 3 but network total 5. Both answers are correct for their different objectives.

Continue learning

Union Find | Dijkstra Shortest Paths | Collections

Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.