I am trying to create a local search heuristic to solve the TSP, and this process seems to be failing. I have generated a random Hamiltonian cycle and stored it in outgoing[] with outgoing[i] denoting the vertex which one of the edges originating at i points towards. distances[a][b] denotes the distance from vertex a to vertex b. However, whenever I run this code, instead of optimizing the Hamiltonian cycle which I pass in outgoing, the algorithm simply creates the new cycle 0->numcities-2->1->numcities-1. It should simply switch the outgoing vertices repeatedly if it can improve upon the distance of a vertex to its outgoing vertex. I am probably overlooking something minor, but I simply cannot figure out what I did wrong. I will be running this many times by the way, and that is what the boolean changed is used for.
for(int i = 0; i < numcities; i++)
{
for(int j = i+1; j < numcities; j++)
{
if(distances[i][outgoing[i]] + distances[j][outgoing[j]] > distances[i][outgoing[j]] + distances[j][outgoing[i]] && i != outgoing[j] && j != outgoing[i])
{
changed = true;
int temp = outgoing[j];
outgoing[j] = outgoing[i];
outgoing[i] = temp;
}
}
}