/** Does not handle Graphs of 1 or fewer nodes */ public Graph kruskal(Graph g) { boolean add = false; Graph mst = new Graph(); // initialize graph Vector edges = g.getEdges(); // get edges Collections.sort(edges); // sort edges // find mst for (int i = 0; i < edges.size(); ++i) { Edge edge = (Edge) edges.get(i); // get edge KNode[] ends = edge.getEnds(); // get ends if (!mst.containsNode(ends[0])) { mst.addNode(ends[0]); // check for first end add = true; } if (!mst.containsNode(ends[1])) { mst.addNode(ends[1]); // check other end add = true; } if (add) // if either end is new add edge { mst.addEdge(edge); add = false; } else // ensure trees are connected if nodes are contained { if (!mst.pathBetween(ends)) mst.addEdge(edge); } } return mst; }
public int compareTo(Object o2) { Edge e2 = (Edge) o2; if (this.getWeight() < e2.getWeight()) return -1; else if (this.getWeight() > e2.getWeight()) return 1; else if (this.getWeight() == e2.getWeight()) return 0; return -2; }
public String printEdges(KNode n) { Vector edgeSet = new Vector(); for (int i = 0; i < edges.size(); ++i) { if (((Edge) edges.get(i)).connectsNode(n)) edgeSet.add((Edge) edges.get(i)); } if (edgeSet.size() == 0) return "-none-"; String value = ""; for (int i = 0; i < edgeSet.size(); ++i) { Edge e = (Edge) edgeSet.get(i); value += n + "" + e + "" + e.otherEnd(n) + "\n"; } return value; }