How to resolve the algorithm Sorting algorithms/Merge sort step by step in the FunL programming language
How to resolve the algorithm Sorting algorithms/Merge sort step by step in the FunL 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 FunL programming language
Source code in the funl programming language
def
sort( [] ) = []
sort( [x] ) = [x]
sort( xs ) =
val (l, r) = xs.splitAt( xs.length()\2 )
merge( sort(l), sort(r) )
merge( [], xs ) = xs
merge( xs, [] ) = xs
merge( x:xs, y:ys )
| x <= y = x : merge( xs, y:ys )
| otherwise = y : merge( x:xs, ys )
println( sort([94, 37, 16, 56, 72, 48, 17, 27, 58, 67]) )
println( sort(['Sofía', 'Alysha', 'Sophia', 'Maya', 'Emma', 'Olivia', 'Emily']) )
You may also check:How to resolve the algorithm Problem of Apollonius step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm Stable marriage problem step by step in the Racket programming language
You may also check:How to resolve the algorithm Executable library step by step in the Clojure programming language
You may also check:How to resolve the algorithm Loops/Downward for step by step in the M4 programming language
You may also check:How to resolve the algorithm Singleton step by step in the ActionScript programming language