Skip to content

Add Merge Sort in OCaml#5991

Open
alope107 wants to merge 4 commits into
TheRenegadeCoder:mainfrom
alope107:ocamlMerge
Open

Add Merge Sort in OCaml#5991
alope107 wants to merge 4 commits into
TheRenegadeCoder:mainfrom
alope107:ocamlMerge

Conversation

@alope107
Copy link
Copy Markdown
Contributor

I Am Adding a New Code Snippet in an Existing Language

  • I fixed Add Merge Sort in OCaml #5989
  • I did not include any extra folders/libraries
  • I named the pull request using Add {PROJECT} in {LANGUAGE} format

I experimented both with a top-down and bottom-up mergesort, as the problem description does not specify which one should be implemented. I ended up going with the bottom-up approach, it felt like a better fit for OCaml than the top-down one.

@github-actions github-actions Bot added enhancement Any code that improves the repo merge sort See: https://sampleprograms.io/projects/merge-sort/ labels May 23, 2026
Copy link
Copy Markdown
Collaborator

@rzuckerm rzuckerm left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, but this does not look like anything that is recognizable as a merge sort. Please add some comments as to what this is doing.

@alope107
Copy link
Copy Markdown
Contributor Author

Added some comments, hope they make the bottom up merge sort a bit easier to see.

I recognize that top down is the more commonly seen variant of merge sort, but at least Wikipedia recognizes both top down and bottom up versions as merge sort.

The problem description doesn't specify a version. You'll see that this implementation exactly matches what it states:

  1. Divide the sorted list into lists of 1 element.
  2. Continually merge the lists together until they become a single list. Do the merge as follows:
    1. Compare the smallest items in each of the two lists to be merged.
    2. Move the smaller of the two to the new merged list
    3. Repeat until there are no unmerged items

I did implement the top-down version as well (see the first commit in the chain), but OCaml's linked lists feel awkward to repeatedly find the midpoint of, and using an array feels less idiomatic. The bottom up allows a simple map to cover the entire splitting part for us, and uses a bottom-up folding pattern instead of the function call stack to coordinate merges.

@alope107 alope107 requested a review from rzuckerm May 23, 2026 00:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Any code that improves the repo merge sort See: https://sampleprograms.io/projects/merge-sort/

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add Merge Sort in OCaml

3 participants