| 1 | (* A generic sort: slices in many orders and of every length up to 40 come out |
| 2 | in order, holding what they held; and a sort by a record's field. *) |
| 3 | module Sorted; |
| 4 | import Out, Rt, Ints := Order(I64, below), ByAge := Order(Person, younger); |
| 5 | |
| 6 | type Person = record name: []const U8; age: I64; end; |
| 7 | |
| 8 | proc below(a, b: I64): BOOL; |
| 9 | begin |
| 10 | return a < b; |
| 11 | end; |
| 12 | |
| 13 | proc younger(a, b: Person): BOOL; |
| 14 | begin |
| 15 | return a.age < b.age; |
| 16 | end; |
| 17 | |
| 18 | proc main*; |
| 19 | var |
| 20 | a: [40]I64; count: [10]I64; n, i, kind, seed: I64; |
| 21 | people: [4]Person; |
| 22 | begin |
| 23 | seed := 7; |
| 24 | for n := 0 to 40 do |
| 25 | for kind := 0 to 3 do |
| 26 | for i := 0 to 9 do count[i] := 0; end; |
| 27 | for i := 0 to n - 1 do |
| 28 | seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; |
| 29 | if kind = 0 then a[i] := seed mod 10; (* at random, with repeats *) |
| 30 | elsif kind = 1 then a[i] := i mod 10; (* rising *) |
| 31 | elsif kind = 2 then a[i] := 9 - i mod 10; (* falling *) |
| 32 | else a[i] := 5; (* all equal *) |
| 33 | end; |
| 34 | INC(count[a[i]]); |
| 35 | end; |
| 36 | Ints.sort(a[0..n]); |
| 37 | for i := 0 to n - 1 do |
| 38 | if (i > 0) and (a[i - 1] > a[i]) then Rt.stop("out of order"); end; |
| 39 | DEC(count[a[i]]); |
| 40 | end; |
| 41 | for i := 0 to 9 do |
| 42 | if count[i] # 0 then Rt.stop("not what it held"); end; |
| 43 | end; |
| 44 | end; |
| 45 | end; |
| 46 | people := [{name: "Ana", age: 41}, {name: "Bo", age: 7}, {name: "Cy", age: 90}, {name: "Di", age: 23}]; |
| 47 | ByAge.sort(people); |
| 48 | for i := 0 to 3 do Out.str(people[i].name); Out.char(' '); Out.int(people[i].age); Out.ln; end; |
| 49 | end; |
| 50 | |
| 51 | end Sorted. |