
This problem arises frequently in applications and often appears as a sub-problem within other optimization problems.
Select a cut with at least one edge crossing the cut, but no tree edges (a tree edge is any edge that has been selected in a previous step). Select a lightest edge crossing the cut and add it to the tree.
The method terminates when there are no eligible cuts. At this point, the tree edges define a minimum spanning tree if the graph is connected and a minimum spanning forest, if it is not. Notice that the greedy method does not say what cut to select or how to do it efficiently. It turns out that no matter how these choices are made, the greedy method produces a minimum spanning tree (or forest). This establishes the correctness of any specific algorithm that implements the general greedy method, meaning that one doesn't need to prove correctness separately for each algorithm. Defining algorithms in terms of a general method like this sheds light on what is essential and what is incidental, and helps clarify the fundamental similarities and differences among algorithms. The correctness of the greedy method can be established by showing that it maintains the following invariant.
There is a minimum spanning forest containing all of the tree edges.
The invariant is trivially true before the first tree edge is selected. Suppose now, that it is true before one step of the greedy method. Let $e=\{x,y\}$ be the selected edge, and let $F$ be a minimum spanning forest containing all the previously selected tree edges. If $e$ is an edge in $F$, then after the rule is applied, $F$ still contains all the tree edges. If $e$ is not in $F$, then there must be a path from $x$ to $y$ in $F$ and some edge $e'$ on this path must be in the cut from which $e$ was selected, as shown below.

Since the cut contains no tree edges, $e'$ cannot be a tree edge, so $\weight(e) \leq \weight(e')$. Consequently, the forest obtained from $F$ by replacing $e'$ with $e$ is also a minimum spanning forest. This result is summarized in the following theorem.
Theorem 1. The edges selected by the greedy method define a minimum spanning tree if the graph is connected and a minimum spanning forest if it is not.
Select a lightest edge with exactly one endpoint in the tree containing $s$ and add it to the set of tree edges.
When it is no longer possible to apply the selection rule, the selected edges define a minimum spanning tree.
The key to an efficient implementation of Prim's algorithm is a data structure that allows the lightest edge incident to the partial tree to be quickly identified. One way to do this is to use a heap to store the vertices that are on the border between the partial tree and the remainder of the graph. A border vertex is one that is not in the tree but does have one or more edges linking it to tree vertices. A border vertex $u$ is stored in the heap, using a key equal to the weight of the lightest edge joining $u$ to a tree vertex. The identity of that lightest edge is stored as $\link(u)$. Note that this implies that if $u$ has the smallest key of any vertex in the heap, then $\link(u)$ is the lightest edge with one endpoint in the tree. With these definitions, the selection rule can be rephrased as follows.
Remove the vertex $u$ with the smallest key from the border heap and add $\link(u)$ to the set of tree edges.
To ensure that this leads to a valid algorithm, it's also necessary to maintain the following invariant.
Before each selection step, the border heap defines the set of border vertices and for each border vertex $u$, $\link(u)$ is the lightest edge joining $u$ to a tree vertex.
Initially, the start vertex $s$ is the only tree vertex, so the invariant can be established by setting $\link(u)=\{s,u\}$ for each neighbor $u$ of $s$ and adding $u$ to the border heap with a key value of $\weight(\link(u))$.
To maintain the invariant after removing $u$ from the heap, the neighbors of $u$ are scanned. For each neighor $v$ that is being scanned for the first time $\link(v)$ is set to $\{u,v\}$ and $v$ is added to the heap with a key value of $\weight(\link(v))$. For each neighbor that is already in the border set, the edge $\{u,v\}$ is compared with $\link(v)$. If $\{u,v\}$ is lighter than $\link(v)$, $\link(v)$ is set to $\{u,v\}$ and the key of $v$ in the heap is reduced to $\weight(\link(v))$.
When there are no more border vertices the algorithm completes, and for each tree vertex $u\neq s$, $\link(u)$ can be viewed as the edge connecting $u$ to its “parent” in the minimum spanning tree. A Javascript implementation of the main part of the algorithm is shown below.
In this implementation $\link(u)$ is initialized to $-1$ for all $u \neq s$ and $\link(s)$ is set to zero. Once a vertex $u$ is scanned, $\link(u) \geq 0$. Also, the heap is intialized to contained $s$. This means that the first loop iteration serves to establish the invariant, while the remaining iterations maintain the invariant as described above.
Prim's algorithm can be implemented using any heap data structure, but it is most commonly implemented using an array heap. If the heap operations are excluded, the running time is $O(m)$, since the innermost loop is executed no more than $2m$ times. The heap operations include $n-1$ insert operations, $n-1$ deletemin operations and up to $m-n$ changekey operations, all of which reduce the key value. This leads to a worst-case running time of $O(m \log_d n + n d\log_d n)$ when an array heap is used. The value of $d$ can be selected to yield the best tradeoff between the operations using siftup and those using siftdown Specifically, if $d= 2 + \lfloor m/n \rfloor$, the running time becomes $O(m\log_d n)$. For dense graphs, say $m\geq n^{3/2}$, it is $O(m \log n / \log (2+m/n)) = O(m)$. For sparse graphs, say $m = n \log n$, it is $O(n (\log n)^2 / \log\log n)$ and for extremely sparse graphs, say $m = 3n$, it is simply $O(n\log n)$. Hence, at all graph densities, Prim's algorithm is very efficient, and is optimal for dense graphs, where arguably, it is most important to be optimally efficient. This, combined with its simplicity of implementation makes it an attractive choice in practice.
The graph shown below demonstrates that there are worst-case examples for which the performance of Prim's algorithm closely matches the analysis.

If the algorithm starts at the leftmost vertex and examines the edges incident to each vertex in decreasing order of their weight, every insert and changekey operation causes a vertex to move from the bottom of the heap to the top, maximizing the number of steps performed by siftup. This example can be easily extended to arbitrary values of $n$ and by taking subgraphs, one can construct worst-case examples of any density. It is worth noting that the example does depend critically on the order in which the edges are examined. For example, if the edges incident to each vertex are examined in increasing order of weight, the number of siftup steps drops to one per changekey. If the edges are examined in random order, the expected number of siftup steps per changekey is $O(1)$. So in this case, the best choice of $d$ is a small constant (say 2 or 4) and the expected running time is $O(m + n \log n)$.
If Prim's algorithm is implemented using a Fibonacci heap, its worst-case running time is $O(m + n \log n)$, which does provide a modest improvement over the worst-case when array heaps are used. In practice however, the added complexity of Fibonacci heaps puts it at a disadvantage in most situations.
A complete Javascript implementation of Prim's algorithm appears below. This version has been generalized so that it can be applied to graphs that are not fully connected. In that case, it produces a minimum spanning forest of the graph.
In the common case of a connected graph, the body of the outer for-loop is executed one time, producing a minimum spanning tree starting from the first vertex. For a disconnected graph, each iteration of the outer loop computes a minimum spanning tree of a distinct connnected component. The version shown above has been abridged for clarity. The complete version (available on the web app) supports execution tracing and performance statistics. Note that the return value is a triple that includes an array of the edges numbers for the edges in the tree, as well as a trace string and a statistics object (not shown).
If the following script is run in the scratch pad of the web app
let g = new Graph();
g.fromString("{a[b:3 d:2 e:5] b[a:3 c:7 f:4] c[b:7 d:1 f:2] " +
"d[a:2 c:1 e:3] e[a:5 d:3 f:1] f[b:4 c:2]}");
let [,ts] = mstP(g,2,1);
log(ts);
it produces the following output.
The graph is shown at the top. On each iteration of the inner while loop, the border vertex with the lightest edge connecting it to the partially constructed forest is shown, along with its lightest edge, and the heap.
To compare the experimental performance to the predicted worst-case performance, enter the following script into the web app.
let n = 1024; let d = n-1; let m = d*n/2;
let g = hardcaseP(n, m);
log(`n=${n} density=${g.m/g.n}`);
let t0, t1, steps, stats;
t0 = Date.now(); [,,stats] = mstP(g); t1 = Date.now();
log(`prim time=${t1-t0}ms steps/m=${(stats.steps/g.m).toFixed(2)}`);
t0 = Date.now(); [,,stats] = mstP(g,2); t1 = Date.now();
log(`prim_2 time=${t1-t0}ms steps/m=${(stats.steps/g.m).toFixed(2)}`);
When $m=n(n-1)/2$, the function $\textit{hardcaseP}(n,m)$ produces
a graph like the worst-case example shown earlier,
with $n$ vertices and $m$ edges.
The optional third argument to mstP specifies the
heap parameter $d$.
When it is omitted, $d$ is chosen to match the edge density.
Running this code on graphs of increasing size produces the output
n=128 density=63.5 prim time=1ms steps/m=5.01 prim_2 time=2ms steps/m=8.50 n=256 density=127.5 prim time=12ms steps/m=5.01 prim_2 time=6ms steps/m=9.43 n=512 density=255.5 prim time=10ms steps/m=5.00 prim_2 time=19ms steps/m=10.39 n=1024 density=511.5 prim time=49ms steps/m=5.00 prim_2 time=86ms steps/m=11.37Observe that when $d$ matches the edge density, the number of steps per edge remains constant, even as the edge density grows, as predicted by the worst-case analysis. When $d=2$, the number of steps per edge increases by about one additional step each time $n$ is doubled. For the largest graph shown, the number of steps per edge is more than double that for the case when $d$ matches the edge density. The impact on running time is somewhat smaller, as the siftup steps take less time than the siftdown steps. The impact of $d$ is greatest when the graphs are maximally dense. Reducing the density for the last test case shows a much smaller effect.
n=1024 density=128 prim time=11ms steps/m=4.72 prim_2 time=13ms steps/m=5.87To evaluate the program's performance on random graphs, replace the second line of the code in the web app with
let g = randomGraph(n,d); g.randomWeights(randomFraction);The randomWeights function takes a random number generator as its first argument. In this case, the specified function generates uniform random numbers in $[0,1]$. Running this on graphs of increasing size produces the output
n=128 density=63.5 prim time=1ms steps/m=2.93 prim_2 time=1ms steps/m=2.33 n=256 density=127.5 prim time=2ms steps/m=2.87 prim_2 time=2ms steps/m=2.20 n=512 density=255.5 prim time=9ms steps/m=2.88 prim_2 time=8ms steps/m=2.11 n=1024 density=511.5 prim time=81ms steps/m=2.86 prim_2 time=81ms steps/m=2.07Notice that in this case, fixing the heap parameter at 2 produces fewer steps per edge and faster run times. This reflects the fact that with random edge weights, the number of changekey operations is much smaller than in the worst-case, greatly reducing the number of siftup operations. Consequently, the performance is largely determined by the overhead of the inner loop of Prim's algorithm, not the data structure operations.
If the current edge $e$ has endpoints in different trees, add $e$ to the set of tree edges.
Note that when $e$'s endpoints are in different trees, one can define a cut that has one of the trees by itself on one side of the cut, with all other vertices on the other side.
The merge sets data structure can be used to keep track of the vertices in the different trees. This leads directly to the following implementation (abridged for clarity).
If an efficient comparison sorting algorithm is used to sort the edges, then Kruskal's algorithm takes $O(m \log n)$ time. If the edges can be sorted using a linear-time algorithm such as radix sort, this drops to $O(m \alpha(m,n))$. The simplicity of Kruskal's algorithm makes it an attractive choice, but its performance is critically dependent on the method used to sort the edges.
Remove the first tree $T_1$ from the queue. If there is an edge joining $T_1$ to some other tree, let $T_2$ be the tree with the lightest edge linking it to $T_1$; remove $T_2$ from the queue, combine the two trees and add the combined tree to the end of the queue.
To make this efficient, the merge sets data structure is used to keep track of the vertices in each tree (as in Kruskal's algorithm), and leftist heaps are used to keep track of the edges incident to each tree. By selecting the lightest edge in the heap for $T_1$, the algorithm can quickly identify $T_2$, then merge the vertex sets for the two trees and meld their heaps. The melds are done using lazy melding. Items in the heap are considered to be deleted if they are dummy items introduced by lazy melds, or they correspond to edges whose endpoints now belong to the same tree. This latter condition is determined using a function call, eliminating the need to explicitly delete items from the heaps.
A Javascript implementation of the algorithm appears below.
Note that each tree in the queue is represented by the vertex that identifies the tree's set within the merge sets data structure. Also, in the array of heaps, $h[u]$ is the heap of edges incident to the tree whose identifier in the merge sets data structure is $u$. Hence, the line
h[trees.merge(tu, tv)] = eph.lazyMeld(h[tu], h[tv]);
combines the heaps associated with the trees whose identifiers
are $tu$ and $tv$ and assigns the resulting heap to the identifier of
the new set formed when the sets identified by $tu$ and $tv$ are
combined.
To see the algorithm in action, enter the following text into the scratch pad of the web app.
let g = new Graph();
g.fromString('{a[b:3 d:2] b[a:3 c:7] c[b:7 d:1] d[a:2 c:1] ' +
'e[f:1 g:3] f[e:1 g:2 h:3] g[e:3 f:2 h:1] i[j:5] j[i:5]}');
let [,ts] = mstCT(g, 1);
log(ts);
Running this code yields
The trace string returned by mstCT shows the graph and for each iteration of the main loop, it shows the edge selected in that iteration, plus the resulting queue state and the vertex sets for the trees that are not singletons. If the penultimate line is changed to
let [,ts] = mstCT(g, 2);
it also shows the heap of edges incident to each newly formed tree.
Note that dummy and retired heap items are not shown, so some of the
new heaps are effectively empty.
The running time of the algorithm is dominated by the calls to findmin at the start of each iteration. During each execution of findmin, the deleted items near the top of the heap are removed and sub-heaps with roots that are not deleted are combined using the heapify operation. This processing dominates the running time. All other operations can be done in $O(m)$ time.
To analyze the time required for the findmins, the execution of the algorithm is divided into passes where a pass ends when all heaps that were on the queue at the start of the pass have been removed and combined with some other heap. For now, let's ignore the time consumed by operations on the merge sets data structure. Observe that during a pass, every tree that was on the queue at the start of the pass is combined with at least one other tree during the pass. Consequently, the trees on the heap during the $k$-th pass have at least $2^k$ vertices and the number of passes is $\leq \lg n$. Now, note that any two trees selected during the same pass are vertex-disjoint, since they are on the heap at the same time. This implies that the total size of the heaps that are processed in a single pass is at most $2m + n-1$, so each edge appears in at most two heaps and the number of dummy items introduced by lazy melds is at most $n-1$.
To complete the analysis, let $m_i$ be the size of the heap on the $i$-th call to findmin and let $k_i$ be the number of items removed from the heap during that execution of findmin. Note that $\sum_{i=1}^{n-1} m_i \leq (2m+n-1)\lg n$ and that the time required for the heapify in the $i$-th findmin is $O(k_i \max(1,\log(m_i/k_i))$ based on the earlier analysis of heapify.
A findmin is called small if $k_i \leq (m_i/(\lg n)^2)-1$; otherwise, it is called large. Excluding time spent on operations on the merge sets data structure, the total time spent on the small findmins is $$ O\left( \sum_{i=1}^{n-1} \frac{m_i}{(\log n)^2} \log m_i\right) =O\left( \sum_{i=1}^{n-1} \frac{m_i}{\log n}\right) =O(m) $$ The total time spent on the large findmins is $$ O\left( \sum_{i=1}^{n-1} k_i \log \frac{m_i }{ m_i/(\log n)^2}\right) =O\left( \sum_{i=1}^{n-1} k_i \log\log n\right) =O( m\log\log n ) $$ This implies that the number of merge sets operations is $O(m\log\log n)$ and so the time spent on merge sets operations is $O(\alpha(m\log\log n, n)m\log\log n) = O(m \log\log n)$.

The value of $n$ is fixed at $10^3$, while $m$ ranges from $10^3$ to $10^6$. The chart shows the function values divided by $m$, to emphasize the differences among them. The two curves that decrease with $m$ are associated with Prim's algorithm. The $m+n\log n$ curve is for the version that uses Fibonacci heaps. While that version appears to have an advantage at moderate densities, experimental commparisons show that the version using array heaps is consistently faster, due to the relative simplicity of its data structuures. The Cheriton-Tarjan algorithm has an edge at the lowest densities, but the advantage over Prim's algorithm is modest.
The results below compare Prim's algorithm with Kruskal's algorithm and the Cheriton-Tarjan algorithm. The first three sets of results show how the performance scales with density, and clearly demonstrates Prim's advantage as the density grows.
The second set of results show how the performance scales with graph size for the lowest density graphs. Here, Kruskal's advantage over Prim shows up clearly. It's also clear that the asymptotic advantage of the Cheriton and Tarjan algorithm will eventually make itself felt as its number of steps per edge is essentially flat, while for the others, this metric is increasing with $n$.