function cycle_max = perm1_cycle_max ( p )

%*****************************************************************************80
%
%% perm1_cycle_max() returns the length of a longest cycle in a permutation.
%
%  Discussion:
%
%    The permutation is assumed to be over the integers 1 through N.
%
%  Example:
%
%      P = 2, 3, 9, 6, 7, 8, 5, 4, 1
%
%      Cycles: ( 1, 2, 3, 9 ), ( 4, 6, 8 ), ( 5, 7 )
% 
%      cycle_max = 4
%
%  Licensing:
%
%    This code is distributed under the MIT license. 
%
%  Modified:
%
%    13 November 2022
%
%  Author:
%
%    John Burkardt.
%
%  Input:
%
%    integer p(n): the permutation to be analyzed.  
%
%  Output:
%
%    integer cycle_max: the length of a longest cycle in P.
%
  n = length ( p );

  cycle_max = 0;

  for i = 1 : n

    j = p(i);
    cycle_length = 1;

    while ( j ~= i )
      j = p(j);
      cycle_length = cycle_length + 1;
    end

    cycle_max = max ( cycle_max, cycle_length );

  end

  return
end

