PROGRAM Quick1( Input, Output );   { Quicksort program }

CONST Size = 20;

TYPE List = ARRAY[1..Size] OF INTEGER;

VAR
  L: List;      { Array to be sorted }
  K: INTEGER;

PROCEDURE Swap( VAR X, Y : INTEGER );
VAR Temp:INTEGER;
BEGIN
  Temp := X;
  X := Y;
  Y := Temp
END;     { Swap }

PROCEDURE QSort(
      Left,    { Position of first element }
      Right:   { Position of last element }
       INTEGER
      );

VAR
  Up, Down, Pivot: INTEGER;

BEGIN
              { Partition values }
  Up := Left;
  Down := Right;
  Pivot := L[ (Left+Right) div 2 ];   { Set pivot value }
  REPEAT
    WHILE L[Up] < Pivot  DO           { Scan forward }
      Up := Up+1;
    WHILE Pivot < L[Down]  DO         { Scan backward }
      Down := Down-1;
    IF  Up <= Down  THEN              { Swap & continue scans }
      BEGIN
        SWAP( L[Up], L[Down] );
        Up := Up+1;
        Down := Down-1
      END
  UNTIL  Up > Down;                   { until scan pointers cross }

              { Sort each partition part }
  IF Left < Down
    THEN  QSort( Left, Down );  { Sort left part }
  IF Up < Right
    THEN  QSort( Up, Right );  { Sort right part }
END;     { QSort }


BEGIN    { Main = QuickSortDemo }
  FOR K := 1 TO Size DO
    L[K] := TRUNC( RANDOM*900 );
  FOR K := 1 TO Size DO
    WRITE( L[K]:4 );
  QSort( 1, Size );
  Writeln;
  FOR K := 1 TO Size DO
    WRITE( L[K]:4 );
END.     { QuickSortDemo }