

ReachSet = {0}; // You can use any node... UnReachSet = {1, 2, ..., N1}; SpanningTree = {}; while ( UnReachSet ≠ empty ) { Find edge e = (x, y) such that: 1. x ∈ ReachSet 2. y ∈ UnReachSet 3. e has smallest cost SpanningTree = SpanningTree ∪ {e}; ReachSet = ReachSet ∪ {y}; UnReachSet = UnReachSet  {y}; } 




ReachSet = {0}; // You can use any node... UnReachSet = {1, 2, ..., N1}; SpanningTree = {}; while ( UnReachSet ≠ empty ) { Find edge e = (x, y) such that: 1. x ∈ ReachSet 2. y ∈ UnReachSet 3. e has smallest cost SpanningTree = SpanningTree ∪ {e}; ReachSet = ReachSet ∪ {y}; UnReachSet = UnReachSet  {y}; } 
public void Prim( ) { int i, j, k, x, y; boolean[] Reached = new boolean[NNodes]; // Reach/unreach nodes int[] predNode = new int[NNodes]; // Remember min cost edge /*  ReachSet = {0}; UnReachSet = {1, 2, ..., N1};  */ Reached[0] = true; for ( i = 1; i < NNodes; i++ ) { Reached[i] = false; } predNode[0] = 0; // This is not necessary.... // Just make sure we don't have a bogus edge /* ===================================================== UnReachSet will decreas by 1 node in each iteration There are NNodes1 unreached nodes; so we can loop NNodes1 times and UnReachSet will become empty ! ===================================================== */ for ( k = 1; k < NNodes; k++) // Loop NNodes1 times (UnReachSet = empty) { /* ================================================================ Find min. cost link between: reached node > unreached node ================================================================ */ x = y = 0; for ( i = 0; i < NNodes; i++ ) for ( j = 0; j < NNodes; j++ ) { if ( Reached[i] && ! Reached[j] && LinkCost[i][j] < LinkCostes[x][y] ) { x = i; // Link (i,j) has lower cost !!! y = j; } } /* =============================== Add e (x,y) to Spanning tree =============================== */ predNode[y] = x; /* ========================================== ReachSet = ReachSet ∪ {y} UnReachSet = UnReachSet  {y} ========================================== */ Reached[y] = true; } printMinCostEdges( predNode ); // Print the min, cost spanning tree } 
How to run the program:

Output:
Input graph: Representation: LinkCost[][]: * 3 * 2 * * * * 4 3 * * * * * * 4 * * * * 6 * 1 * 2 * 2 * 6 * 1 * * * * * * * 1 * * * * 8 * * 1 * * * 8 * * * * * * * 8 * * * * 4 2 * * * * * * 4 * * * 8 * * * * ============================================= ReachSet = 0 Min cost edge: (0,3)cost = 2 ReachSet = 0 3 Min cost edge: (3,4)cost = 1 ReachSet = 0 3 4 Min cost edge: (0,1)cost = 3 ReachSet = 0 1 3 4 Min cost edge: (0,8)cost = 4 ReachSet = 0 1 3 4 8 Min cost edge: (1,7)cost = 4 ReachSet = 0 1 3 4 7 8 Min cost edge: (7,2)cost = 2 ReachSet = 0 1 2 3 4 7 8 Min cost edge: (2,5)cost = 1 ReachSet = 0 1 2 3 4 5 7 8 Min cost edge: (5,6)cost = 8 ReachSet = 0 1 2 3 4 5 6 7 8 ======================================== Edges of the Min. cost spanning tree: 0 > 0 0 > 1 7 > 2 0 > 3 3 > 4 2 > 5 5 > 6 1 > 7 0 > 8 
Graphically: