// mstw.java // demonstrates minimum spanning tree with weighted graphs // to run this program: C>java MSTWApp //////////////////////////////////////////////////////////////// class Edge { public int srcVert; // index of a vertex starting edge public int destVert; // index of a vertex ending edge public int distance; // distance from src to dest // ------------------------------------------------------------- public Edge(int sv, int dv, int d) // constructor { srcVert = sv; destVert = dv; distance = d; } // ------------------------------------------------------------- } // end class Edge //////////////////////////////////////////////////////////////// class PriorityQ { // array in sorted order, from max at 0 to min at size-1 private final int SIZE = 20; private Edge[] queArray; private int size; // ------------------------------------------------------------- public PriorityQ() // constructor { queArray = new Edge[SIZE]; size = 0; } // ------------------------------------------------------------- public void insert(Edge item) // insert item in sorted order { int j; for(j=0; j= queArray[j].distance ) break; for(int k=size-1; k>=j; k--) // move items up queArray[k+1] = queArray[k]; queArray[j] = item; // insert item size++; } // ------------------------------------------------------------- public Edge removeMin() // remove minimum item { return queArray[--size]; } // ------------------------------------------------------------- public void removeN(int n) // remove item at n { for(int j=n; j newDist) // if new edge shorter, { thePQ.removeN(queueIndex); // remove old edge Edge theEdge = new Edge(currentVert, newVert, newDist); thePQ.insert(theEdge); // insert new edge } // else no action; just leave the old vertex there } // end if else // no edge with same destination vertex { // so insert new one Edge theEdge = new Edge(currentVert, newVert, newDist); thePQ.insert(theEdge); } } // end putInPQ() // ------------------------------------------------------------- } // end class Graph //////////////////////////////////////////////////////////////// class MSTWApp { public static void main(String[] args) { Graph theGraph = new Graph(); theGraph.addVertex('A'); // 0 (start for mst) theGraph.addVertex('B'); // 1 theGraph.addVertex('C'); // 2 theGraph.addVertex('D'); // 3 theGraph.addVertex('E'); // 4 theGraph.addVertex('F'); // 5 theGraph.addEdge(0, 1, 6); // AB 6 theGraph.addEdge(0, 3, 4); // AD 4 theGraph.addEdge(1, 2, 10); // BC 10 theGraph.addEdge(1, 3, 7); // BD 7 theGraph.addEdge(1, 4, 7); // BE 7 theGraph.addEdge(2, 3, 8); // CD 8 theGraph.addEdge(2, 4, 5); // CE 5 theGraph.addEdge(2, 5, 6); // CF 6 theGraph.addEdge(3, 4, 12); // DE 12 theGraph.addEdge(4, 5, 7); // EF 7 System.out.print("Minimum spanning tree: "); theGraph.mstw(); // minimum spanning tree System.out.println(); } // end main() } // end class MSTWApp ////////////////////////////////////////////////////////////////