function [ a1, a2 ] = i4vec2_sort_insert_a ( n, a1, a2 )

%*****************************************************************************80
%
%% i4vec2_sort_insert_a() uses an ascending insertion sort on an I4VEC2.
%
%  Licensing:
%
%    This code is distributed under the MIT license. 
%
%  Modified:
%
%    24 June 2022
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Donald Kreher, Douglas Simpson,
%    Combinatorial Algorithms,
%    CRC Press, 1998, page 11.
%
%  Input:
%
%    integer N, the number of items.
%
%    integer A1(N), A2(N), the pair of arrays to be sorted.
%
%  Output:
%
%    integer A1(N), A2(N), the sorted arrays.
%
  for i = 2 : n

    x1 = a1(i);
    x2 = a2(i);

    j = i - 1;

    while ( 1 <= j )

      if ( a1(j) < x1 | ( a1(j) == x1 & a2(j) < x2 ) )
        break
      end

      a1(j+1) = a1(j);
      a2(j+1) = a2(j);
      j = j - 1;

    end

    a1(j+1) = x1;
    a2(j+1) = x2;

  end

  return
end
