function p = next_perm ( p )

%*****************************************************************************80
%
%% NEXT_PERM computes the lexicographic permutation successor.
%
%  Example:
%
%    RANK  Permutation
%
%       0  1 2 3 4
%       1  1 2 4 3
%       2  1 3 2 4
%       3  1 3 4 2
%       4  1 4 2 3
%       5  1 4 3 2
%       6  2 1 3 4
%       ...
%      23  4 3 2 1
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    12 January 2011
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Donald Kreher, Douglas Simpson,
%    Combinatorial Algorithms,
%    CRC Press, 1998,
%    ISBN: 0-8493-3988-X,
%    LC: QA164.K73.
%
%  Parameters:
%
%    Input, integer N, the number of values being permuted.
%    N must be positive.
%
%    Input, integer P(N), the input permutation, or [] if the
%    first permutation is to be returned.
%
%    Output, integer P(N), the successor permutation.
%    If the input permutation was the last in the ordered list,
%    then the output permutation is [].
%
  n = length ( p );

  if ( all ( p == 0 ) )
    p = 1 : n;
    return
  end
%
%  Seek I, the highest index for which P(I) < P(I+1).
%
  i = n - 1;

  while ( 1 )

    if ( i <= 0 )
      p = [];
      return
    end

    if ( p(i) < p(i+1) )
      break
    end

    i = i - 1;

  end
%
%  Look for the highest J index so that P(I) < P(J).
%
  j = n;
  while ( p(j) <= p(i) )
    j = j - 1;
  end
%
%  Interchange P(I) and P(J).
%
  t    = p(i);
  p(i) = p(j);
  p(j) = t;
%
%  Reverse the order of P(I+1:N).
%
  p(i+1:n) = p(n:-1:i+1);

  return
end
