Files
rose-ash/lib/ocaml/baseline/pancake_sort.ml
giles 5d71be364e
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 26s
ocaml: phase 5.1 pancake_sort.ml baseline (in-place pancake sort, 9 flips -> 910)
Each pass:
  1. find_max in [0..size-1]
  2. if max not at the right end, flip max to position 0 (if needed)
  3. flip 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.

  pancake_sort [3;1;4;1;5;9;2;6]
  = 9 flips * 100 + a.(0) + a.(n-1)
  = 9 * 100 + 1 + 9
  = 910

The output combines flip count and sorted endpoints, so the test
verifies both that the sort terminates and that it sorts correctly.

Tests two inner functions closing over the same Array, ref-based
two-pointer flip, and downto loop with conditional flip dispatch.

77 baseline programs total.
2026-05-09 16:03:22 +00:00

34 lines
694 B
OCaml

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]