This repository was archived by the owner on Jun 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsorter.pas
More file actions
70 lines (62 loc) · 2.2 KB
/
sorter.pas
File metadata and controls
70 lines (62 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
unit sorter;
(* a simple quick sort routine for sorting an array of integers *)
interface
uses modulo;
const
qvindexer = (8 * (upper + 1) - 1); (* quad sized rub * integer / ansichar multiplier *)
(* this makes it twice as many as a quad sized rub value, but it indexes > 255 *)
qupper = (64 * (qvindexer + 1) - 1); (* block size 32K *)
type
compare = function(i, j: word): boolean;
lquad = packed array [0 .. qupper] of word;
function sort(a: lquad; w: compare): lquad;
function lessThan(i, j: word): boolean;
implementation
var
index: lquad;
function lessThan(i, j: word): boolean;
begin
lessthan := index[i] < index[j];
end;
procedure swap(i, j: word);
var
t: word;
begin
t := index[i];
index[i] := index[j];
index[j] := t;
end;
function partition(left, right, pivotIndex: word): word;
var
storeIndex, i: word;
begin
swap(pivotIndex, right);
storeIndex := left;
for i := left to right - 1 do
if lessThan(i, pivotIndex) then
begin
swap(i, storeIndex);
storeIndex := storeIndex + 1;
end;
swap(storeIndex, right);
partition := storeIndex;
end;
procedure qsort(left, right: word);
var
pivotIndex, pivotNewIndex: word;
begin
if right > left then
begin
pivotIndex := left + (right - left) div 2;
pivotNewIndex := partition(left, right, pivotIndex);
qsort(left, pivotNewIndex - 1);
qsort(pivotNewIndex + 1, right);
end;
end;
function sort(a: lquad; w: compare): lquad;
begin
index := a;
qsort(0, length(a));
sort := index;
end;
end.