program AbstrKod;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TIntArray = array [0..1023] of Integer;
      //slusni lide indexuji od 0


//sjednoceni 2 poli do pole pole1
procedure Sjednot(var pole1:TIntArray;pole2:TIntArray;pole1_c:Integer;pole2_c:Integer);
var i:Integer;
begin
 for i := 0 to pole2_c-1 do
   pole1[pole1_c+i] := pole2[i];
end;//procedure

procedure BubbleSort(var ar:TIntArray;cnt:Integer);
var prohozeno:boolean;
    i:Integer;
begin
 repeat
   prohozeno := false;
   for i := 0 to cnt-2 do
    begin
     if (ar[i] > ar[i+1]) then
      begin
       //prohozeni 2 prvku
       ar[i]   := ar[i] + ar[i+1];
       ar[i+1] := ar[i] - ar[i+1];
       ar[i]   := ar[i] - ar[i+1];
       prohozeno := true;
      end;//
    end;//for i
 until (not prohozeno);
end;//procedure

//vraci primo pivot
function FindPivot(ar:TIntArray;l,r:Integer):Integer;
var pivots:TIntArray;
    i:Integer;
begin
 for i := 0 to 2 do pivots[i] := ar[Random(r)+l];
 BubbleSort(pivots,3);
 Result := pivots[1];
end;//function

procedure QuickSort(var ar:TIntArray;l, r: integer);
var
  i, j, pivot, pom: integer;
begin
  i := l;
  j := r;
  pivot := FindPivot(ar,l,r);
  repeat
    while ((i < r) and (ar[i] < pivot)) do i := i + 1;
    while ((j > l) and (pivot < ar[j])) do j := j - 1;
    if (i <= j) then
     begin
      if (i < j) then
       begin
        pom := ar[i];
        ar[i] := ar[j];
        ar[j] := pom;
       end;
      if (i < r) then i := i + 1;
      if (j > l) then j := j - 1
     end;
  until (i > j);
  if (j > l) then quicksort(ar, l, j);
  if (i < r) then quicksort(ar, i, r)
end;


//sjednoceni 2 poli + serazeni quicksortem
procedure ProvedNeco(source,add:TIntArray;var vysledek:TIntArray;src_count,add_count:Integer);
 begin
  Sjednot(source,add,src_count,add_count);
  QuickSort(source,0,(src_count+add_count)-1);
 end;//procedure

//main
var Ar1,Ar2,vysledek:TIntArray;
begin
  try
    Randomize();

    //testovaci hodnoty
    Ar1[0]  := 20;
    Ar1[1]  := 50;
    Ar1[2]  := 40;
    Ar1[3]  := 10;

    Ar2[0]  := 22;
    Ar2[1]  := 44;

    ProvedNeco(Ar1,Ar2,vysledek,4,2);

    readln;
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
end.
