Schell Sort

While there are several built in alternatives for sorting, this example is the shell sort algorithm for the vArray global variable.  The ShellSort procedure needs to know the number of elements in the array to sort, and whether to sort ascending or descending.  The Boolean flag is set to True for ascending order, and False for descending order. Fill the vArray elements from index 1 through index Count.

procedure ShellSort(count: integer; b: boolean);
var
  i,j,k: integer;
  v: variant;
label break;
begin
  k:=count div 2;
  while k>0 do begin
    for i:=k to pred(count) do begin
      for j:=i-k+1 downto 1 do begin
        if b then begin
          if vArray(j)<=vArray(j+k) then goto break;
        end
        else
          if vArray(j)>=vArray(j+k) then goto break;
        v:=vArray(j); {exchange j and j+k elements}
        SetArray(j,vArray(j+k));
        SetArray(j+k,v);
      end;
break: end;
    k:=k div 2;
  end;
end;

var n: integer;
begin
  if who=1 then begin
    Output(eClear);
    DimArray(20); {when you use vArray don't forget to dimension it}
    for n:=1 to 20 do SetArray(n,Random(100));
    ShellSort(20,true);
    for n:=1 to 20 do writeln(vArray(n));
  end;
end;

Notes:  You may want to file this example away in your collection of useful routines.  Note, the TArray variables have a built in sort method which would be used for TArray variables instead of a routine like today's example.