This function provides Ascending / Descending sorting using Shell algorithm. Relatively fast and can be easily adopted to be used with any kind of arrays.
(much faster compared with quick sort with medium arrays, may be slower in case of larger arrays(>1000 items), but always overcomes it in worst cases)
Here is the function code with some testing procedure:
const
_asc = 1;
_des = -1;
procedure ShellSort(Direction: integer; var ArrayToBeSorted: array of integer);
var
buf: integer;
i, j, n, k: integer;
begin
k := GetArrayLength(ArrayToBeSorted);
n := k - 1;
k := k shr 1;
while (k > 0) do begin
i := 0;
while (i <= n-k) do begin
j := i;
while (j >= 0) and ((ArrayToBeSorted[j] - ArrayToBeSorted[j + k]) * Direction > 0) do begin
buf := ArrayToBeSorted[j];
ArrayToBeSorted[j] := ArrayToBeSorted[j+k];
ArrayToBeSorted[j + k] := buf;
if (j > k) then dec(j, k) else j := 0;
end;
inc(i, 1);
end;
k := k shr 1;
end;
end;
procedure ActivateServer();
var
t: array of integer;
i: integer;
TestArraySize: integer;
begin
TestArraySize := 50;
setarraylength(t, TestArraySize);
WriteLn('Array of random numbers:');
for i := 0 to TestArraySize-1 do begin
t[i] := Random(-30000, 30000);
WriteLn(IntToStr(t[i]));
end;
WriteLn('Ascending sorting:');
ShellSort(_asc, t);
for i := 0 to TestArraySize-1 do begin
WriteLn(IntToStr(t[i]));
end;
WriteLn('Descending sorting:');
ShellSort(_des, t);
for i := 0 to TestArraySize-1 do begin
WriteLn(IntToStr(t[i]));
end;
end;