raz / sbcl / lib / Sort.raz

30 lines · 804 B · raw · history · last change 55bc6c0d

1(* Sorting a slice in place, by heapsort: n log n at most, and no memory
2 of its own. *)
3module Sort(T; less: proc(a, b: T): BOOL);
4
5(* the element at i moved down the heap of the first n elements *)
6proc sift(s: []T; i, n: INT);
7var child: INT; t: T;
8begin
9 child := 2 * i + 1;
10 while child < n do
11 if child + 1 < n and less(s[child], s[child + 1]) then INC(child); end;
12 if not less(s[i], s[child]) then return; end;
13 t := s[i]; s[i] := s[child]; s[child] := t;
14 i := child;
15 child := 2 * i + 1;
16 end;
17end;
18
19proc sort*(s: []T);
20var i, n: INT; t: T;
21begin
22 n := LEN(s);
23 for i := n div 2 - 1 to 0 by -1 do sift(s, i, n); end;
24 for i := n - 1 to 1 by -1 do
25 t := s[0]; s[0] := s[i]; s[i] := t;
26 sift(s, 0, i);
27 end;
28end;
29
30end Sort.