How to resolve the algorithm Sorting algorithms/Merge sort step by step in the Standard ML programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sorting algorithms/Merge sort step by step in the Standard ML programming language

Table of Contents

Problem Statement

The   merge sort   is a recursive sort of order   nlog(n). It is notable for having a worst case and average complexity of   O(nlog(n)),   and a best case complexity of   O(n)   (for pre-sorted input). The basic idea is to split the collection into smaller groups by halving it until the groups only have one element or no elements   (which are both entirely sorted groups). Then merge the groups back together so that their elements are in order. This is how the algorithm gets its   divide and conquer   description.

Write a function to sort a collection of integers using the merge sort.

The merge sort algorithm comes in two parts: The functions in pseudocode look like this:

Note:   better performance can be expected if, rather than recursing until   length(m) ≤ 1,   an insertion sort is used for   length(m)   smaller than some threshold larger than   1.   However, this complicates the example code, so it is not shown here.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sorting algorithms/Merge sort step by step in the Standard ML programming language

Source code in the standard programming language

fun merge cmp ([], ys) = ys
  | merge cmp (xs, []) = xs
  | merge cmp (xs as x::xs', ys as y::ys') =
      case cmp (x, y) of GREATER => y :: merge cmp (xs, ys')
                       | _       => x :: merge cmp (xs', ys)
;
fun merge_sort cmp [] = []
  | merge_sort cmp [x] = [x]
  | merge_sort cmp xs = let
      val ys = List.take (xs, length xs div 2)
      val zs = List.drop (xs, length xs div 2)
    in
      merge cmp (merge_sort cmp ys, merge_sort cmp zs)
    end
;
merge_sort Int.compare [8,6,4,2,1,3,5,7,9]

  

You may also check:How to resolve the algorithm Speech synthesis step by step in the BASIC256 programming language
You may also check:How to resolve the algorithm Tree traversal step by step in the C programming language
You may also check:How to resolve the algorithm Arithmetic/Complex step by step in the Free Pascal programming language
You may also check:How to resolve the algorithm Numeric error propagation step by step in the J programming language
You may also check:How to resolve the algorithm File input/output step by step in the XPL0 programming language