Algorithm Implementation/Sorting/Merge sort

Merge Sort
You start with an unordered sequence. You create N empty queues. You loop over every item to be sorted. On each loop iteration, you look at the last element in the key. You move that item into the end of the queue which corresponds to that element. When you are finished looping you concatenate all the queues together into another sequence. You then reapply the procedure described but look at the second last element in the key. You keep doing this until you have looped over every key. When you complete this process the resulting sequence will be sorted as described above.

Key Comparing
Keys are compared in the following way: Let ka be the key of the one item, called item A, let kb be the key of the other item, called item B. Let ka(i) be the ith entry in the key ka, where the first entry is at index 0. Let i = 0. If the keys are less than i elements long then the keys are equal. If ka(i) < kb(i), then item A is ordered before item B. If ka(i) > kb(i), then item B is ordered before item A. If ka(i) = kb(i), then add one to i, and return the line under "Let i = 0."

Time Cost
Let ni be the number of items in the sequence to be sorted. N is number of integers that each key element can take. Let nk be the number of keys in each item.

The total time to sort the sequence is thus O(nk(ni + N)).

Common Lisp
Naive implementation, translation of pseudocode found at Wikipedia.

Simpler Implementation in a somewhat more functional style.

C++
A recursive implementation using the C++14 standard library.

Haskell
sort :: Ord a => [a] -> [a] sort []        =  [] sort [x]       =  [x] sort xs        =  merge (sort ys) (sort zs) where (ys,zs) = splitAt (length xs `div` 2) xs    merge [] y=y merge x []=x merge (x:xs) (y:ys) | x<=y = x:merge xs (y:ys) | otherwise = y:merge (x:xs) ys

A slightly more efficient version only traverses the input list once to split (note that  takes linear time in Haskell):

Prolog
This is an ISO-Prolog compatible implementation of merge sort.

Python
A "standard" mergesort:

An alternative method, using a recursive algorithm to perform the merging in place (except for the O(log n) overhead to trace the recursion) in O(n log n) time:

JavaScript
Separate into two functions:

OCaml
Using a functor to create modules that specialize sorting lists of a given type with a particular comparison function:

Implementazioni di algoritmi/Merge sort