choose any vertex r
d[v] ← ∞ for all v ≠ r
d[r] ← 0
let tree T be an empty tree
while T has < n vertices do {
let v be a vertex not in T with minimum value d[v]
add v to T
for edges vw do {
if w is not in T then {
if \ell[v,w] < d[w] then {
d[w] ← \ell[v,w]
p[w] ← v
}
}
}
}
/* The tree defined by the edges p[v] (v ∈ V) is the MST. */
Each iteration does \(O(1)\) priority queue operations for each vertex or edge.
using heaps or rb-tree gives time \(O(m \log n)\)
using an array gives time \(O(n^2)\)
using Fibonacci heap gives time \(O(m + n \log n)\)
initialize T to a forest containing n vertices & no edges
/* so T contains n different trees */
for each edge e, in order of nondecreasing length \ell(e) do
if e joins 2 different trees of T then add e to T
[RUN THE ALGORIHM ON THE EXAMPLE GRAPH.]
[Step 2] We keep track of the trees of T using an array tree[1..n].
tree[i] identifies the tree that currently contains vertex i.
The last line of Kruskal's algorithm,
“If e joins 2 different trees of T then add e to T” is implemented as follows:
{
let edge e = uv
a <- tree[u]; b <- tree[v]
if a <> b then
for i <- 1 to n do
if tree[i] = a then
tree[i] <- b
}
JOIN
to combine the trees.