Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Implementation

An implementation of Prim's algorithm is shown in Program gif. This implementation is almost identical to the version of Dijkstra's algorithm given in Program gif. In fact, there are only four differences between the two algorithms. These are found on lines 3, 23-25, 34, and 36.

   program53218
Program: Prim's algorithm.

The PrimsAlgorithm method takes two arguments. The first is an undirected graph instance. We assume that the graph is edge-weighted and that the weights are ints. The second argument is the number of the start vertex, tex2html_wrap_inline71118.

The PrimsAlgorithm method returns a minimum-cost spanning tree represented as an undirected graph. Therefore, the return value is a Graph.

The running time of Prim's algorithm is asymptotically the same as Dijkstra's algorithm. That is, the worst-case running time is

displaymath71546

when adjacency lists are used, and

displaymath71547

when adjacency matrices are used to represent the input graph.


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.