function [ ja, a ] = rearrange_crs ( n, nz_num, ia, ja, a )

%*****************************************************************************80
%
%% rearrange_crs() sorts a CRS matrix.
%
%  Discussion:
%
%    This routine guarantees that the entries in the CR matrix
%    are properly sorted.
%
%    After the sorting, the entries of the matrix are rearranged in such
%    a way that the entries of each column are listed in ascending order
%    of their column values.
%
%    The matrix A is assumed to be stored in Compressed Row Storage (CRS)
%    format.  Only the nonzero entries of A are stored.  The vector JA stores the
%    column index of the nonzero value.  The nonzero values are sorted
%    by row, and the compressed row vector IA then has the property that
%    the entries in A and JA that correspond to row I occur in indices
%    IA(I) through IA(I+1)-1.
%
%  Licensing:
%
%    This code is distributed under the MIT license. 
%   
%  Modified:
%
%    25 March 2008
%
%  Author:
%
%    Original C version by Lili Ju
%    This version by John Burkardt
%
%  Input:
%
%    integer N, the order of the system.
%
%    integer NZ_NUM, the number of nonzeros.
%
%    integer IA(N+1), the compressed row indices..
%
%    integer JA(NZ_NUM), the column indices.
%
%    real A(NZ_NUM), the matrix values.
%
%  Output:
%
%    integer JA(NZ_NUM), may have been rearranged by the sorting.
%
%    real A(NZ_NUM), the matrix values may have been moved somewhat
%    because of the sorting.
%
  for i = 1 : n

    for k = ia(i) : ia(i+1) - 2
      for l = k + 1 : ia(i+1) - 1

        if ( ja(l) < ja(k) )
          t     = ja(l);
          ja(l) = ja(k);
          ja(k) = t;

          t    = a(l);
          a(l) = a(k);
          a(k) = t;
        end

      end
    end

  end

  return
end
 
