Skip to content

Implement Dynarray.sort#14848

Open
Jeannalyse wants to merge 8 commits into
ocaml:trunkfrom
Jeannalyse:feature/dynarray-stable-sort-sub
Open

Implement Dynarray.sort#14848
Jeannalyse wants to merge 8 commits into
ocaml:trunkfrom
Jeannalyse:feature/dynarray-stable-sort-sub

Conversation

@Jeannalyse
Copy link
Copy Markdown
Contributor

This PR adds new standard library functions : Dynarray.stable_sort_sub, Dynarray.stable_sort and Dynarray.sort.
These functions were suggested here : #13343 (comment) .
They use Array.stable_sort_sub, so the sorting algorithm is the same as in Array. They consider a change in length to be a programming error, and raise an exception when they detect one.

Note that Dynarray.sort is, in fact, an alias for Dynarray.stable_sort : I figured that a default sorting function was a good thing to have, and that it could be later replaced by an other algorithm if needed.

I have modified the tests in testsuite/tests/misc/sort_sub.ml so that they test both Array.stable_sort_sub and Dynarray.stable_sort_sub.

I came up with three versions in total, each committed separately :

  • version 1 : adapts the code in Array by using Dynarray.get, Dynarray.set, Dynarray.blit etc.
  • version 2 : adapts the code in Array by using unsafe_get on the backing arrays
  • version 3 : directly uses Array.stable_sort_sub on the backing array

My benchmarks show that the third one is the fastest, and it is also the shortest code-wise, so I only kept this one in the final commit. The benchmarks can be found on my fork on the branch named benchmarks/dynarray-stable-sort-sub. Here are some results :

Command Mean [s] Min [s] Max [s] Relative
./benchmarks.opt 1 1.509 ± 0.019 1.490 1.547 1.24 ± 0.03
./benchmarks.opt 2 1.359 ± 0.021 1.333 1.402 1.12 ± 0.03
./benchmarks.opt 3 1.213 ± 0.024 1.188 1.260 1.00

Please don't hesitate to ask questions and suggest improvements.

@nojb
Copy link
Copy Markdown
Contributor

nojb commented Jun 5, 2026

cc @ocaml/stdlib

@nojb nojb added the stdlib label Jun 5, 2026
@Jeannalyse Jeannalyse force-pushed the feature/dynarray-stable-sort-sub branch from dd0cf0c to 88a1abc Compare June 5, 2026 13:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants