diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index d2b6abc9..08741db4 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -110,6 +110,7 @@ "prime_factors.ml": 17, "pythagorean.ml": 16, "queens.ml": 2, + "quickselect.ml": 5, "quicksort.ml": 44, "roman.ml": 44, "reverse_int.ml": 54329, diff --git a/lib/ocaml/baseline/quickselect.ml b/lib/ocaml/baseline/quickselect.ml new file mode 100644 index 00000000..cb652a35 --- /dev/null +++ b/lib/ocaml/baseline/quickselect.ml @@ -0,0 +1,25 @@ +let rec quickselect arr lo hi k = + if lo = hi then arr.(lo) + else begin + let pivot = arr.(hi) in + let i = ref lo in + for j = lo to hi - 1 do + if arr.(j) < pivot then begin + let t = arr.(!i) in + arr.(!i) <- arr.(j); + arr.(j) <- t; + i := !i + 1 + end + done; + let t = arr.(!i) in + arr.(!i) <- arr.(hi); + arr.(hi) <- t; + if !i = k then arr.(!i) + else if !i < k then quickselect arr (!i + 1) hi k + else quickselect arr lo (!i - 1) k + end + +;; + +let a = [|7; 2; 9; 1; 5; 6; 3; 8; 4|] in +quickselect a 0 8 4 diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index ba8e479f..a0861bdc 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,13 @@ _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 — quickselect.ml baseline (Hoare quickselect + median of [7;2;9;1;5;6;3;8;4] = 5). Lomuto partition scheme: + recursively partitions on the last element as pivot, narrows the + range to the side containing the kth index. Mutates the array + in place via `.(i) <- v`. Verifies that array literal syntax + works for in-place mutation paths, not just reads. 138 baseline + programs total. - 2026-05-10 Phase 5.1 — array literals + lis.ml baseline (longest increasing subsequence on a 9-element array = 6). Added parser support for `[| e1; e2; ...; en |]` syntax: desugars to