I'm trying to design a 2-opt local search heuristic for the TSP in Java, but my algorithm seems to be flawed. Given a nearest neighbor circuit as in input, it somehow makes the circuit worse. Nearest neighbor: http://goo.gl/uI5X6; After ten seconds of 2-opt: http://goo.gl/5AGJ1. My code is below. What's wrong with my implementation? Location[] location is simply a list of the nodes of the "graph", each with latitude and longitude and distance calculation between it and another node.
public HamiltonianCircuit execute(Location[] locations) {
long startTime = System.currentTimeMillis();
while (true) {
for (int i = 0; i < locations.length; i++) {
for (int k = 0; k < locations.length; k++) {
if (System.currentTimeMillis() - startTime >= 10000) {
return new HamiltonianCircuit(locations);
}
Location a = locations[i];
Location b = locations[(i + 1) % locations.length];
Location c = locations[k];
Location d = locations[(k + 1) % locations.length];
double distanceab = a.distanceBetween(b);
double distancecd = c.distanceBetween(d);
double distanceac = a.distanceBetween(c);
double distancebd = b.distanceBetween(d);
double change = (distanceab + distancecd) -
(distanceac + distancebd);
if (change > 0) {
locations[k] = a;
locations[i] = c;
}
}
}
}
}