diff --git a/lib/ocaml/baseline/binary_heap.ml b/lib/ocaml/baseline/binary_heap.ml new file mode 100644 index 00000000..108d8ca5 --- /dev/null +++ b/lib/ocaml/baseline/binary_heap.ml @@ -0,0 +1,47 @@ +let parent i = (i - 1) / 2 +let lchild i = 2 * i + 1 +let rchild i = 2 * i + 2 + +let swap a i j = + let t = a.(i) in + a.(i) <- a.(j); + a.(j) <- t + +let rec sift_up a i = + if i > 0 && a.(parent i) > a.(i) then begin + swap a i (parent i); + sift_up a (parent i) + end + +let rec sift_down a n i = + let l = lchild i and r = rchild i in + let smallest = ref i in + if l < n && a.(l) < a.(!smallest) then smallest := l; + if r < n && a.(r) < a.(!smallest) then smallest := r; + if !smallest <> i then begin + swap a i !smallest; + sift_down a n !smallest + end + +let push a size x = + a.(!size) <- x; + size := !size + 1; + sift_up a (!size - 1) + +let pop a size = + let m = a.(0) in + size := !size - 1; + a.(0) <- a.(!size); + sift_down a !size 0; + m + +;; + +let a = Array.make 20 0 in +let s = ref 0 in +List.iter (fun x -> push a s x) [9; 4; 7; 1; 8; 3; 5; 2; 6]; +let total = ref 0 in +for _ = 1 to 9 do + total := !total * 10 + pop a s +done; +!total diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 6b361776..d521d489 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -11,6 +11,7 @@ "bf_full.ml": 6, "bisect.ml": 141, "bigint_add.ml": 28, + "binary_heap.ml": 123456789, "bits.ml": 21, "balance.ml": 3, "base_n.ml": 17, diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index 97c7934e..ee42b769 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,14 @@ _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-10 Phase 5.1 — binary_heap.ml baseline (array-backed + binary min-heap, push 9 random values then pop in sorted order + → digits concat to 123456789). Standard heap mechanics: parent + /lchild/rchild index arithmetic, sift-up after push, sift-down + after pop. Push [9;4;7;1;8;3;5;2;6], pop returns 1..9 in order; + fold-as-decimal yields 123456789. Tests recursive sift_up / + sift_down, ref-tracked external size, in-place array swap, + combined push/pop with mutable closure. 152 baseline programs total. - 2026-05-10 Phase 5.1 — rolling_hash.ml baseline (Rabin-Karp rolling hash for substring matching, count "abc" in "abcabcabcabcabcabc" = 6). Polynomial hash mod 1000003 with