interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / merge-sort / merge-sort.om

129 lines · 2366 bytes Raw Blame History
1note Rosetta Code task "Sorting algorithms/Merge sort": https://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text minus "-"
7text data "38 27 43 3 9 82 10 -5 61 3 0 -19 77 14 50 8"
8global vals long 16
9global tmp long 16
10note emit writes every byte of a to stdout; a short write is retried, an error exits 1
11fn emit a view uchar * to void
12o = ulong 0
13while lt o len a bound 4096
14k = write 1 a o sub len a o
15if le k 0
16exit 1
17end
18o = add o ulong k
19end
20end
21note emitu writes n in decimal; 20 digits hold every ulong
22fn emitu n ulong to void
23d = new uchar 20 0
24i = ulong 20
25v = n
26while true bound 20
27i = sub i 1
28put d i uchar add rem v 10 48
29v = div v 10
30if eq v 0
31break
32end
33end
34emit part d i sub 20 i
35end
36note emiti writes a signed n; the magnitude is taken as a ulong so the minimum long cannot overflow
37fn emiti n long to void
38if lt n 0
39emit minus
40emitu add bitcast ulong not n 1
41else
42emitu ulong n
43end
44end
45note parse reads the decimal numbers in s (separated by spaces, an optional - sign) into vals and
46note returns how many; one pass over s, so the loop is bounded by len s
47fn parse s view uchar * to ulong
48n = ulong 0
49v = long 0
50sg = long 1
51dig = false
52for i ulong len s
53c = get s i
54if eq c 45
55sg = long -1
56else
57if and ge c 48 le c 57
58v = add mul v 10 long sub c 48
59dig = true
60else
61if dig
62put vals n mul sg v
63n = add n 1
64end
65v = long 0
66sg = long 1
67dig = false
68end
69end
70end
71if dig
72put vals n mul sg v
73n = add n 1
74end
75ret n
76end
77note show writes vals[0..n-1] separated by spaces, then a newline
78fn show n ulong to void
79for i ulong n
80if gt i 0
81emit sp
82end
83emiti get vals i
84end
85emit nl
86end
87note msort sorts vals[lo..hi-1]: sort both halves, merge them into tmp, copy back; the merge writes
88note one element per pass, so hi-lo <= 16 passes; the halves are strictly smaller, so recursion ends
89fn msort lo ulong hi ulong to void
90if le sub hi lo 1
91ret
92end
93m = add lo shr sub hi lo 1
94msort lo m
95msort m hi
96i = lo
97j = m
98k = lo
99while lt k hi bound 16
100left = false
101if ge j hi
102left = true
103else
104if lt i m
105if le get vals i get vals j
106left = true
107end
108end
109end
110if left
111put tmp k get vals i
112i = add i 1
113else
114put tmp k get vals j
115j = add j 1
116end
117k = add k 1
118end
119for x ulong sub hi lo
120put vals add lo x get tmp add lo x
121end
122end
123fn main to int
124n = parse data
125show n
126msort 0 n
127show n
128ret 0
129end