OK Here is for fun the program that count the number of swaps in a random permutation:
%%%%%%%%%%%%%%%%%%
% swapfactor.m
function swapidx = swapfactor(P)
% Decompose P as list of of atomic swap permutation
mask=false(size(P));
swapidx = [];
% Loop until all element are marked
while ~all(mask)
[C mask] = getonecycle(P, mask);
if length(C)>1
sC = [C(1:end1) C(2:end)];
swapidx = [swapidx; sC]; %#ok
end
end
end % swapfactor
function [C mask]= getonecycle(P, mask)
% Get on cycle
k0=find(~mask,1,'first');
k=k0;
Pk=0;
C=[];
while Pk~=k0;
mask(k)=true;
Pk=P(k);
C(end+1)=Pk; %#ok
k=Pk;
end
% reshape in column
C=C(:);
end % getonecycle
%%%%%
% swap.m
function P = swap(P, i1, i2)
[P(i2) P(i1)] = deal(P(i1),P(i2));
end % swap
% Test in command line
P=randperm(10)
% Decompose P as list of of atomic swap permutation
swapidx = swapfactor(P);
ns = size(swapidx,1);
fprintf('Numer of swaps = %d\n', ns);
% Test
n=length(P);
Q=1:n;
for j=1:ns
Q=swap(Q,swapidx(j,1),swapidx(j,2));
end
Q
% Bruno
