ocaml: phase 5.1 binary_heap.ml baseline (min-heap sort 9 vals -> 123456789)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s

Array-backed binary min-heap with explicit size tracking via ref:

  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

Push [9;4;7;1;8;3;5;2;6], pop nine times -> 1,2,3,4,5,6,7,8,9.
Fold-as-decimal: ((((((((1*10+2)*10+3)*10+4)*10+5)*10+6)*10+7)*10+8)*10+9 = 123456789.

Tests recursive sift_up + sift_down, in-place array swap,
parent/lchild/rchild index arithmetic, combined push/pop session
with refs.

152 baseline programs total.
This commit is contained in:
2026-05-10 06:43:46 +00:00
parent 19d0ef0f38
commit 0ef26b20f3
3 changed files with 56 additions and 0 deletions

View File

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

View File

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

View File

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