ocaml: phase 6 List.sort upgraded to mergesort (+3 tests, 528 total)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s

The previous List.sort was O(n^2) insertion sort. Replaced with a
straightforward mergesort:

  split lst    -> alternating-take into ([odd], [even])
  merge xs ys  -> classic two-finger merge under cmp
  sort cmp xs  -> base cases [], [x]; otherwise split + recursive
                  sort on each half + merge

Tuple destructuring on the split result is expressed via nested
match — let-tuple-destructuring would be cleaner but works today.

This benefits sort_uniq (which calls sort first), Set.Make.add via
sort etc., and any user program using List.sort. Stable_sort is
already aliased to sort.
This commit is contained in:
2026-05-09 03:01:28 +00:00
parent a0e8b64f5c
commit 8188a82a58
3 changed files with 43 additions and 5 deletions

View File

@@ -146,14 +146,30 @@
let rec sort cmp xs =
begin
let rec insert x ys =
match ys with
| [] -> [x]
| h :: t -> if cmp x h <= 0 then x :: ys else h :: insert x t
let rec split lst =
match lst with
| [] -> ([], [])
| [x] -> ([x], [])
| x :: y :: rest ->
(match split rest with
| (a, b) -> (x :: a, y :: b))
in
let rec merge xs ys =
match xs with
| [] -> ys
| x :: xs' ->
(match ys with
| [] -> xs
| y :: ys' ->
if cmp x y <= 0 then x :: merge xs' (y :: ys')
else y :: merge (x :: xs') ys')
in
match xs with
| [] -> []
| h :: t -> insert h (sort cmp t)
| [x] -> [x]
| _ ->
(match split xs with
| (a, b) -> merge (sort cmp a) (sort cmp b))
end
let stable_sort = sort