| 1 | (* Sorting a slice in place, in the order less gives: |
| 2 | import ByAge := Sort(Person, younger); |
| 3 | It is a heapsort: no memory of its own, and n log n steps at most, |
| 4 | whatever the order it starts in. Two elements equal by less may |
| 5 | change places. *) |
| 6 | module Sort(T; less: proc(a, b: T): BOOL); |
| 7 | |
| 8 | (* The element at i sinks through s[0..n], a heap with the largest at |
| 9 | its root, to where it is no smaller than its children, 2i+1 and |
| 10 | 2i+2. *) |
| 11 | proc sink(s: []T; i, n: INT); |
| 12 | var c: INT; t: T; |
| 13 | begin |
| 14 | c := 2 * i + 1; |
| 15 | while c < n do |
| 16 | if (c + 1 < n) and less(s[c], s[c + 1]) then INC(c); end; |
| 17 | if not less(s[i], s[c]) then return; end; |
| 18 | t := s[i]; s[i] := s[c]; s[c] := t; |
| 19 | i := c; |
| 20 | c := 2 * i + 1; |
| 21 | end; |
| 22 | end; |
| 23 | |
| 24 | (* Sorts s in place, so that no element is less than the one before |
| 25 | it. Not stable. *) |
| 26 | proc sort*(s: []T); |
| 27 | var i: INT; t: T; |
| 28 | begin |
| 29 | for i := LEN(s) div 2 - 1 to 0 by -1 do sink(s, i, LEN(s)); end; |
| 30 | for i := LEN(s) - 1 to 1 by -1 do |
| 31 | t := s[0]; s[0] := s[i]; s[i] := t; |
| 32 | sink(s, 0, i); |
| 33 | end; |
| 34 | end; |
| 35 | |
| 36 | end Sort. |