liveBook · Manning

Jarnik's algorithm

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

Jarnik's algorithm, commonly called Prim's algorithm, constructs a minimum spanning tree by repeatedly adding the lowest-weight edge connecting the current tree to an outside vertex.

Jarnik's algorithm, commonly called Prim's algorithm, builds a minimum spanning tree by repeatedly choosing the smallest-weight edge from the current tree to an unvisited vertex. The result connects every reachable vertex with minimum combined weight and no cycles. section 4.3

A Swift implementation follows this pattern:

  • Represent edges with comparable, summable weights; WeightedEdge compares edges by weight. section 4.3
  • Store candidate edges in an ascending PriorityQueue and track visited vertices. section 4.3
  • Visit the starting vertex, add its outgoing edges, repeatedly select the smallest valid edge, and visit the newly reached vertex. section 4.3
  • Ignore edges whose destination is already visited; invalid starts return nil. section 4.3

Connecting metropolitan areas

Applied to a weighted graph of 15 U.S. metropolitan areas, the algorithm selects edges such as Seattle–San Francisco (678), Los Angeles–Riverside (50), and Washington–Philadelphia (123), producing a spanning tree with total weight 5,372. section 4.3

Figure 4.7. The highlighted edges represent a minimum spanning tree that connects all 15 MSAs.

Use the highlighted network to trace how selected edges connect all 15 metropolitan areas without cycles. section 4.3

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Explains generic edge types, priority-queue selection, visitation, filtering, validation, and disconnected-graph behavior.
Examples
Demonstrates a 15-metropolitan-area graph and reports its selected edges and total weight of 5,372.
What it assumes
Assumes weighted graph and Swift generic-type familiarity while defining the needed edge and graph structures.
What you can do after
Apply it via Swift's WeightedGraph, WeightedEdge, PriorityQueue, and mst functions.
How it connects
Connects minimum spanning trees with weighted graphs, priority queues, comparable weights, and connected components.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.