I'm trying to make make a program that solves the Minimum Spanning Tree problem. To do this, I have a priority queue of Edge objects which should be sorted according to their corresponding weight field (after that it doesn't really matter, but I've been going by node names).
I'm using the java.util.PriorityQueue
. I've tried just about everything but no way I can think of to implement the compareTo()
function works. It sorts most of the edges correctly, but not all of them. Here's the code for the most basic compareTo()
function I could think of:
@Override
public int compareTo(Object other) {
return toString().compareTo(((Edge) other).toString());
}
The toString()
function outputs first the weight, then the two nodes, so if two nodes A and B were connected with weight 4 it would output
4AB
After putting in a sample graph I end up with the following priority queue:
[1AB, 1BA, 1FH, 2CB, 1CG, 1GC, 1HF, 2EB, 2CD, 3EG, 2BC, 2BE, 3AC, 2GH, 2HG, 5AD, 5EC, 3ED, 2EF, 5CE, 4FD, 2FE, 4FG, 5DA, 2DC, 3GE, 4GF, 3DE, 3CA, 4DF]
Clearly this is not in order, but basically every method of comparing I can think of yields this result.