ocaml: phase 5.1 bsearch.ml baseline (binary search, position sum = 7)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 28s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 28s
Iterative binary search on a sorted int array:
let bsearch arr target =
let n = Array.length arr in
let lo = ref 0 and hi = ref (n - 1) in
let found = ref (-1) in
while !lo <= !hi && !found = -1 do
let mid = (!lo + !hi) / 2 in
if arr.(mid) = target then found := mid
else if arr.(mid) < target then lo := mid + 1
else hi := mid - 1
done;
!found
For [1;3;5;7;9;11;13;15;17;19;21]:
bsearch a 13 = 6
bsearch a 5 = 2
bsearch a 100 = -1
sum = 7
Exercises Array.of_list + arr.(i) + multi-let 'let lo = ... and
hi = ...' + while + multi-arm if/else if/else.
49 baseline programs total.
This commit is contained in:
16
lib/ocaml/baseline/bsearch.ml
Normal file
16
lib/ocaml/baseline/bsearch.ml
Normal file
@@ -0,0 +1,16 @@
|
||||
let bsearch arr target =
|
||||
let n = Array.length arr in
|
||||
let lo = ref 0 and hi = ref (n - 1) in
|
||||
let found = ref (-1) in
|
||||
while !lo <= !hi && !found = -1 do
|
||||
let mid = (!lo + !hi) / 2 in
|
||||
if arr.(mid) = target then found := mid
|
||||
else if arr.(mid) < target then lo := mid + 1
|
||||
else hi := mid - 1
|
||||
done;
|
||||
!found
|
||||
|
||||
;;
|
||||
|
||||
let a = Array.of_list [1;3;5;7;9;11;13;15;17;19;21] in
|
||||
bsearch a 13 + bsearch a 5 + bsearch a 100
|
||||
@@ -7,6 +7,7 @@
|
||||
"bfs.ml": 6,
|
||||
"btree.ml": 39,
|
||||
"brainfuck.ml": 75,
|
||||
"bsearch.ml": 7,
|
||||
"caesar.ml": 215,
|
||||
"calc.ml": 13,
|
||||
"closures.ml": 315,
|
||||
|
||||
Reference in New Issue
Block a user