function p2 = permutation_inverse ( p1 )

%*****************************************************************************80
%
%% permutation_inverse() inverts a permutation.
%
%  Licensing:
%
%    This code is distributed under the MIT license. 
%
%  Modified:
%
%    14 September 2022
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer P1(N), the permutation.
%
%  Output:
%
%    integer P2(N), the inverse permutation
%
  n = permutation_order ( p1 );

  p2 = p1;

  is = 1;

  for i = 1 : n

    i1 = p2(i);

    while ( i < i1 )
      i2 = p2(i1);
      p2(i1) = - i2;
      i1 = i2;
    end

    is = - sign ( p2(i) );
    p2(i) = sign ( is ) * abs ( p2(i) );

  end

  for i = 1 : n

    i1 = - p2(i);

    if ( 0 <= i1 )

      i0 = i;

      while ( true )

        i2 = p2(i1);
        p2(i1) = i0;

        if ( i2 < 0 )
          break;
        end

        i0 = i1;
        i1 = i2;

      end

    end

  end

  return
end

