Files
rose-ash/lib/ocaml/baseline/binary_heap.ml
giles 0ef26b20f3
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
ocaml: phase 5.1 binary_heap.ml baseline (min-heap sort 9 vals -> 123456789)
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.
2026-05-10 06:43:46 +00:00

48 lines
949 B
OCaml

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