Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them.
Page: /drakestapleton/omega-rosetta/blob/main/drafts/rosettacode/binary-search.wiki
# omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
Sign in to star 0 stars 0 watching
About Files History Releases Proposed changes Issues For developers
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}}
3 Omega has no imports, so the small output helpers (emit and friends) are part of the program.
4
5 om2
6 text nl "\n"
7 text minus "-"
8 text found " found at index "
9 text nf " not found"
10 note emit writes every byte of a to stdout; a short write is retried, an error exits 1
11 fn emit a view uchar * to void
12 o = ulong 0
13 while lt o len a bound 4096
14 k = write 1 a o sub len a o
15 if le k 0
16 exit 1
17 end
18 o = add o ulong k
19 end
20 end
21 note emitu writes n in decimal; 20 digits hold every ulong
22 fn emitu n ulong to void
23 d = new uchar 20 0
24 i = ulong 20
25 v = n
26 while true bound 20
27 i = sub i 1
28 put d i uchar add rem v 10 48
29 v = div v 10
30 if eq v 0
31 break
32 end
33 end
34 emit part d i sub 20 i
35 end
36 note emiti writes a signed n; the magnitude is taken as a ulong so the minimum long cannot overflow
37 fn emiti n long to void
38 if lt n 0
39 emit minus
40 emitu add bitcast ulong not n 1
41 else
42 emitu ulong n
43 end
44 end
45 note returns the index of x in the sorted a, or -1; 16 elements need at most 5 halvings
46 fn bsearch a view long 16 x long to long
47 lo = ulong 0
48 hi = ulong 16
49 while lt lo hi bound 16
50 mid = add lo shr sub hi lo 1
51 v = get a mid
52 if eq v x
53 ret long mid
54 end
55 if lt v x
56 lo = add mid 1
57 else
58 hi = mid
59 end
60 end
61 ret -1
62 end
63 fn query a view long 16 x long to void
64 r = bsearch a x
65 emiti x
66 if ge r 0
67 emit found
68 emiti r
69 else
70 emit nf
71 end
72 emit nl
73 end
74 fn main to int
75 a = new long 16 0
76 put a 0 -40
77 put a 1 -12
78 put a 2 -3
79 put a 3 0
80 put a 4 2
81 put a 5 5
82 put a 6 8
83 put a 7 13
84 put a 8 21
85 put a 9 34
86 put a 10 55
87 put a 11 89
88 put a 12 144
89 put a 13 233
90 put a 14 377
91 put a 15 610
92 query a -40
93 query a 0
94 query a 21
95 query a 610
96 query a 7
97 query a 1000
98 query a -41
99 ret 0
100 end
101
102 {{out}}
103
104 -40 found at index 0
105 0 found at index 3
106 21 found at index 8
107 610 found at index 15
108 7 not found
109 1000 not found
110 -41 not found
111