raz / test / bench / heapsort.pas

53 lines · 1.0 KiB · raw · history · last change 62a9b275

1{ Heapsort.raz's twin. }
2program heapsort;
3{$mode objfpc}
4const
5 N = 200000;
6 Rounds = 8;
7var
8 a: array[0..N - 1] of int64;
9 i, r, x, total: int64;
10
11procedure Sift(var s: array of int64; lo, hi: int64);
12var root, child, t: int64;
13begin
14 root := lo;
15 child := 2 * root + 1;
16 while child < hi do begin
17 if (child + 1 < hi) and (s[child] < s[child + 1]) then inc(child);
18 if s[root] >= s[child] then exit;
19 t := s[root];
20 s[root] := s[child];
21 s[child] := t;
22 root := child;
23 child := 2 * root + 1;
24 end;
25end;
26
27procedure Sort(var s: array of int64);
28var i, t: int64;
29begin
30 for i := Length(s) div 2 - 1 downto 0 do Sift(s, i, Length(s));
31 for i := High(s) downto 1 do begin
32 t := s[0];
33 s[0] := s[i];
34 s[i] := t;
35 Sift(s, 0, i);
36 end;
37end;
38
39begin
40 x := 1;
41 total := 0;
42 for r := 1 to Rounds do begin
43 for i := 0 to N - 1 do begin
44 x := (x * 1103515245 + 12345) and $7FFFFFFF;
45 a[i] := x;
46 end;
47 Sort(a);
48 for i := 1 to N - 1 do
49 if a[i - 1] > a[i] then writeln('not sorted');
50 total := total + a[N div 2];
51 end;
52 writeln(total);
53end.