| 1 | (* Sorting a slice in place, by heapsort: n log n at most, and no memory |
| 2 | of its own. *) |
| 3 | module Sort(T; less: proc(a, b: T): BOOL); |
| 4 | |
| 5 | (* the element at i moved down the heap of the first n elements *) |
| 6 | proc sift(s: []T; i, n: INT); |
| 7 | var child: INT; t: T; |
| 8 | begin |
| 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; |
| 17 | end; |
| 18 | |
| 19 | proc sort*(s: []T); |
| 20 | var i, n: INT; t: T; |
| 21 | begin |
| 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; |
| 28 | end; |
| 29 | |
| 30 | end Sort. |