interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / drafts / rosettacode / binary-search.wiki

111 lines · 1905 bytes Raw Blame History
1=={{header|Omegese}}==
2{{works with|omc|sha256 2c824805, aien-dev/omega-mv e5b32567, Linux AArch64}}
3Omega has no imports, so the small output helpers (<code>emit</code> and friends) are part of the program.
4<syntaxhighlight lang="text">
5om2
6text nl "\n"
7text minus "-"
8text found " found at index "
9text nf " not found"
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 returns the index of x in the sorted a, or -1; 16 elements need at most 5 halvings
46fn bsearch a view long 16 x long to long
47lo = ulong 0
48hi = ulong 16
49while lt lo hi bound 16
50mid = add lo shr sub hi lo 1
51v = get a mid
52if eq v x
53ret long mid
54end
55if lt v x
56lo = add mid 1
57else
58hi = mid
59end
60end
61ret -1
62end
63fn query a view long 16 x long to void
64r = bsearch a x
65emiti x
66if ge r 0
67emit found
68emiti r
69else
70emit nf
71end
72emit nl
73end
74fn main to int
75a = new long 16 0
76put a 0 -40
77put a 1 -12
78put a 2 -3
79put a 3 0
80put a 4 2
81put a 5 5
82put a 6 8
83put a 7 13
84put a 8 21
85put a 9 34
86put a 10 55
87put a 11 89
88put a 12 144
89put a 13 233
90put a 14 377
91put a 15 610
92query a -40
93query a 0
94query a 21
95query a 610
96query a 7
97query a 1000
98query a -41
99ret 0
100end
101</syntaxhighlight>
102{{out}}
103<pre>
104-40 found at index 0
1050 found at index 3
10621 found at index 8
107610 found at index 15
1087 not found
1091000 not found
110-41 not found
111</pre>