PROGRAM Sort (Input,Output);
{$R+}

CONST
   MaxLength = 1000;

TYPE
   TestArray = ARRAY[1..MaxLength] OF Integer;

VAR
   A : TestArray;
   Size, Comparisons : Integer;




PROCEDURE GetSize (Var Size : Integer);
Begin
   REPEAT
      Write('Enter size of array (<=',MaxLength,') ');
      Readln(Size);
   UNTIL Size <= MaxLength;
End;



PROCEDURE CreateArray(Var A : TestArray; Size : Integer);
Var
   I : Integer;
Begin
   FOR I := 1 TO Size DO
      A[I] := Random(Size);
End;




PROCEDURE Swap (Var A, B : Integer);
Var
   Temp : Integer;
Begin
   Temp := A;
   A := B;
   B := Temp;
End;





PROCEDURE SortArray(Var A : TestArray;
                    Size : Integer;
                    Var Comparisons : Integer);
Var
   Pass, J, MinIndex : Integer;
Begin
   Comparisons := 0;

   FOR Pass := 1 TO Size-1 DO
     Begin
       MinIndex := Pass;
       FOR J := Pass+1 TO Size DO
         Begin
          Comparisons := Comparisons + 1;
          IF A[J] < A[MinIndex] THEN
             MinIndex := J;
         End;
     Swap(A[Pass],A[MinIndex]);
   End;
End;




PROCEDURE PrintArray(A : TestArray; Size : Integer);
Var
   I : Integer;
Begin
   FOR I := 1 TO Size DO
     Begin
       Write(A[I]:4);
       IF I MOD 15 = 0 THEN
          Writeln;
     End;
   Writeln;
End;




FUNCTION Continue : Boolean;
Var
   Ch : Char;
Begin
   Write('Again? (Y or N) ');
   Readln(Ch);
   IF (Ch='y') OR (Ch='Y') THEN
      Continue := True
   ELSE
      Continue := False;
End;



BEGIN
   REPEAT
      GetSize(Size);
      CreateArray(A,Size);
      SortArray(A,Size,Comparisons);
      PrintArray(A,Size);
      Writeln(Comparisons,' number of comparisons');
   UNTIL NOT Continue;
END.
