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

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:
2026-05-09 10:40:49 +00:00
parent 073ea44fdb
commit a91ff62730
3 changed files with 24 additions and 0 deletions

View 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

View File

@@ -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,

View File

@@ -407,6 +407,13 @@ _Newest first._
binary search tree (`type 'a tree = Leaf | Node of 'a * 'a tree *
'a tree`) with insert + in-order traversal. Tests parametric ADT,
recursive match, List.append, List.fold_left.
- 2026-05-09 Phase 5.1 — bsearch.ml baseline (binary search,
position-sum 6 + 2 + (-1) = 7). Iterative bsearch on a sorted int
array using two index refs `lo`/`hi` and a sentinel `found = -1`.
while loop runs until `lo > hi` or found set. For [1;3;...;21]:
position of 13 = 6, 5 = 2, 100 = -1. Exercises Array.of_list +
arr.(i) + multi-let `let lo = ... and hi = ...` + while + multi-arm
if/else if. 49 baseline programs total.
- 2026-05-09 Phase 5.1 — palindrome.ml baseline (two-pointer
palindrome check, 4 of 6 inputs are palindromes). is_palindrome
walks from both ends meeting in the middle, returning false on