diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 8c6e86e7..805525cc 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -52,6 +52,7 @@ "mutable_record.ml": 10, "option_match.ml": 5, "palindrome.ml": 4, + "pancake_sort.ml": 910, "pascal.ml": 252, "pi_leibniz.ml": 314, "prefix_sum.ml": 66, diff --git a/lib/ocaml/baseline/pancake_sort.ml b/lib/ocaml/baseline/pancake_sort.ml new file mode 100644 index 00000000..23bade9a --- /dev/null +++ b/lib/ocaml/baseline/pancake_sort.ml @@ -0,0 +1,33 @@ +let pancake_sort xs = + let a = Array.of_list xs in + let n = Array.length a in + let flips = ref 0 in + let flip k = + let lo = ref 0 and hi = ref k in + while !lo < !hi do + let tmp = a.(!lo) in + a.(!lo) <- a.(!hi); + a.(!hi) <- tmp; + lo := !lo + 1; + hi := !hi - 1 + done; + flips := !flips + 1 + in + let find_max k = + let m = ref 0 in + for i = 1 to k do + if a.(i) > a.(!m) then m := i + done; + !m + in + for size = n downto 2 do + let mi = find_max (size - 1) in + if mi <> size - 1 then begin + if mi > 0 then flip mi; + flip (size - 1) + end + done; + !flips * 100 + a.(0) + a.(n - 1) +;; + +pancake_sort [3; 1; 4; 1; 5; 9; 2; 6] diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index 93229db5..615a22a8 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,15 @@ _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 — pancake_sort.ml baseline (in-place pancake + sort, 9 flips → 910). Each pass finds the max in [0..size-1], + flips it to position 0 (if needed), then flips the size-prefix to + push max to the end. Inner `flip k` reverses prefix [0..k] using + two pointer-refs lo/hi. Inner `find_max k` walks 1..k tracking + the max-position. `[3;1;4;1;5;9;2;6]` sorts in 9 flips, sum + ends[1, 9] adds 10 → 9*100 + 10 = 910. Tests two inner functions + closing over the same Array, ref-based two-pointer flip, plus + downto loop. 77 baseline programs total. - 2026-05-09 Phase 5.1 — fib_mod.ml baseline (Fibonacci mod prime, fib(100) mod 1000003 = 391360). Iterative two-ref Fibonacci with modular reduction at every step to keep intermediate values