Hi!

I have programmed a very simple function that takes any permutation p of 
[1:n] and finds the next permutation in dictionary order. I know this is 
well-programmed already, but I am learning.

I have programmed the same algorithm both in Julia and Matlab. It is not a 
sophisticated algorithm, but at least I expected it to run faster in Julia 
than Matlab. Quite the contrary.

I attach the .jl file, as well as the corresponding Matlab mfile, if 
someone wants to test it.

Thank you in advance.

P.S. Since collect(permutations(1:n)) seems to return them in dictionary 
order, I guess permutations() somehow should be able to give me the next 
permutation, but I don't know how to do it.

Attachment: nextpermutation_brute!.jl
Description: Binary data

function p = nextpermutation_brute(p)
% EXAMPLE: n=9; p=1:n; tic, for i=2:factorial(n)+2, p=nextpermutation_brute(p); end, toc, p

% We will assume, without checking, that p indeed contains some permutation of [1:n]:
n = size(p,2);
w = find(diff(p)>0);

% Get special case out of the way:
if isempty(w)
    p = 1:n;
    return
end

% Do the main job rather brutely:
w = w(end);
f = p(w);
p(w:end) = sort(p(w:end));
for i = w+1:n
    if p(i)>f
        p(w:end) = p([i w:i-1 i+1:n]);
        return
    end
end

Reply via email to