public MST primGenerateMST() { // populates list of distances List<primState> cost_table = new List<primState>(); for (int i = 0; i < Cities.Length; i++) { for (int j = 0; j < Cities.Length; j++) { primState state = new primState(Cities[i], Cities[j]); if (i == j) { state.setCost(double.PositiveInfinity); } cost_table.Add(state); } } // sort list: O(n^2), worst case. Average case likely O(nlogn), assuming LINQ implements quicksort under-the-hood cost_table = cost_table.OrderBy(State => State.cost).ToList(); // FIND MST // initialize mst to contain the smallest edge MST mst = new MST(); Random random = new Random(); //mst.root = new MSTNode(cost_table.ElementAt(0).startCity); int index = random.Next(0, cost_table.Count); mst.root = new MSTNode(cost_table.ElementAt(index).startCity); mst.root.addChild(new MSTNode(cost_table.ElementAt(index).endCity)); MSTNode curNode = null; cost_table.RemoveAt(0); // create container of cities in the tree for convenience later on ArrayList citiesInMst = new ArrayList(); citiesInMst.Add(mst.root.getCity()); citiesInMst.Add(mst.root.getChildren().ElementAt(0).getCity()); // root only has one child while (citiesInMst.Count < Cities.Length) // grow mst one city at a time until it connects each city (until its size is Cities.length) { foreach (primState curEdge in cost_table) // iterate across remaining (unused) edges from shortest to longest { curNode = mst.findNode(curEdge.startCity); if (curNode != null) // if the start of current edge is already in the tree (expand the current tree, no parallel tree growth for this algorithm)... { // only if the end of current edge is NOT in the tree (no cycles allowed)... if(!citiesInMst.Contains(curEdge.endCity)) { curNode.addChild(new MSTNode(curEdge.endCity)); citiesInMst.Add(curEdge.endCity); cost_table.Remove(curEdge); // O(n) complexity break; } } } } return mst; }