clc;
close all;
tic
n=6;%number of TSP nodes
w=[0,5,1,2,6,5;
    5,0,3,4,2,7;
    1,3,0,4,4,3;
    2,4,4,0,2,7;
    6,2,4,2,0,4;
    5,7,3,7,4,0];
s=[1 2 3 4 5 6];%randperm(6); %initial solution
z=TSP_COST_CALCULATE(n,s,w);
sstar=s;
zstar=z;
while(1)
    for i=1:n-3
        j=i+2;
        while j<=n
            sprime=s;
            temp1=sprime(i+1);
            sprime(i+1)=sprime(j);
            sprime(j)=temp1;
            zprime=TSP_COST_CALCULATE(n,sprime,w);
            if (zprime >= zstar && j<n)
                j=j+2;
            else
                j=j+2;
                if(zprime<zstar)
                    sstar=sprime;
                    zstar=zprime;
                end
            end
            
            
        end
    end
    if s == sstar
        break
    else
        s=sstar;
        z=zstar;
    end
end
disp(sstar);
disp(zstar);
toc
%Calculate Cost of Distances
function cost=TSP_COST_CALCULATE(n,s,w)
cost=0;
for i=1:n-1
    cost=w(s(i),s(i+1))+cost;
end
cost=w(s(n),s(1))+cost;
end
