$ \def\compare{ {\mathrm{compare}} } \def\swap{ {\mathrm{swap}} } \def\sort{ {\mathrm{sort}} } \def\insert{ {\mathrm{insert}} } \def\true{ {\mathrm{true}} } \def\false{ {\mathrm{false}} } \def\BubbleSort{ {\mathrm{BubbleSort}} } \def\SelectionSort{ {\mathrm{SelectionSort}} } \def\Merge{ {\mathrm{Merge}} } \def\MergeSort{ {\mathrm{MergeSort}} } \def\QuickSort{ {\mathrm{QuickSort}} } \def\Split{ {\mathrm{Split}} } \def\Multiply{ {\mathrm{Multiply}} } \def\Add{ {\mathrm{Add}} } \def\cur{ {\mathrm{cur}} } \def\gets{ {\leftarrow} } $
Input:
Output:
a set $F$ of edges in $E$ such that
The graph $T = (V, F)$ is called a minimum spanning tree of $G$
PrimMST(V, E):
initialize set S = {v} with v arbitrary
initialize set F = {} of MST edges, priority queue Q
for each neighbor x of v
add (v, x) to Q with priority w(v, x)
while Q is not empty
(u, v) <- removeMin(Q)
if S doesn't contain v
add (u, v) to F
for each neighbor x of v
add (v, x) to Q with priority w(v, x)
return (S, F)
Definition. Let $G = (V, E)$ be a graph. A cut in $G$ is a partition of $V$ into two (non-empty) subsets $U$ and $V - U$.
Cut Claim. Suppose:
Then:
PrimMST(V, E):
initialize set S = {v} with v arbitrary
initialize set F = {} of MST edges, priority queue Q
for each neighbor x of v
add (v, x) to Q with priority w(v, x)
while Q is not empty
(u, v) <- removeMin(Q)
if S doesn't contain v
add (u, v) to F
for each neighbor x of v
add (v, x) to Q with priority w(v, x)
return (S, F)
Cut claim $\implies$ Prim produces an MST.
Why?
Consider $k$th edge $e_k$ added by Prim
What can we say about the cut $S_k, V - S_k$?
First Conclusion. Every edge $e$ added by Prim’s algorithm is in the MST.
Still to show. All MST edges are added.
Why is this so?
Conclusion. Prim’s algorithm produces an MST.
PrimMST(V, E):
initialize set S = {v} with v arbitrary
initialize set F = {} of MST edges, priority queue Q
for each neighbor x of v
add (v, x) to Q with priority w(v, x)
while Q is not empty
(u, v) <- removeMin(Q)
if S doesn't contain v
add (u, v) to F
for each neighbor x of v
add (v, x) to Q with priority w(v, x)
return (S, F)
Prim’s algorithm:
Prim’s algorithm is greedy
Prim:
Edge Centric View:
Questions:
Kruskal(V, E, w):
C <- collection of components
initially, each vertex is own component
F <- empty collection
# iterate in order of increasing weight
for each edge e = (u, v) in E
if u and v are in different components then
add (u, v) to F
merge components containing u and v
endif
endfor
return F
Claim 1. Every edge added by Kruskal must be in every MST.
Why?
Claim 2. Kruskal produces a spanning tree.
Why?
edges added by Kruskal do not contain cycles (why?)
edges edges added by Kruskal connect graph (why?)
Theorem. Kruskal’s algorithm produces an MST.
Question. How could we implement Kruskal’s algorithm efficiently? What is its running time?