function subseq = permutation_ascending_subsequence ( p )

%*****************************************************************************80
%
%% permutation_ascending_subsequence(): longest ascending subsequence.
%
%  Discussion:
%
%    Although this routine is intended to be applied to a permutation,
%    it will work just as well for an arbitrary vector.
%
%  Licensing:
%
%    This code is distributed under the MIT license. 
%
%  Modified:
%
%    14 September 2022
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer P(N), the permutation to be examined.
%
%  Output:
%
%    integer SUBSEQ(LENGTH), a longest increasing subsequence of A.
%
  n = permutation_order ( p );

  top(1:n) = 0;
  top_prev(1:n) = 0;

  sublen = 0;
  subseq = [];

  if ( n <= 0 )
    return
  end

  for i = 1 : n

    k = 0;

    for j = 1 : sublen
      if ( p(i) <= p(top(j)) )
        k = j;
        break;
      end
    end

    if ( k == 0 )
      sublen = sublen + 1;
      k = sublen;
    end

    top(k) = i;

    if ( 1 < k )
      top_prev(i) = top(k-1);
    else
      top_prev(i) = 0;
    end

  end
%
%  Construct the subsequence.
%
  subseq(1:sublen) = 0;

  j = top(sublen);
  subseq(sublen) = p(j);

  for i = sublen - 1 : -1 : 1
    j = top_prev(j);
    subseq(i) = p(j);
  end

  return
end

