Merge sort (Erlang)

This is an implementation of the merge sort algorithm in Erlang, as applied to cons-based lists. The sorting predicate is user-specified; use lte (defined below) to provide the usual stable sorting of numbers.

There are three functions in the implementation. The first, split, is used to chop the list into two pieces, each of which we will later sort recursively:

A more intuitive way of splitting the list might be to put all odd-positioned elements in one sublist, and the rest in another. This, however, is not stable: a list that is already partially-ordered according to the predicate might be rearranged.

For example, given a binary predicate string_length_lte that returns true iff the first argument is not longer than the second, and the list ("aaa" "bbb" "ccc"), you get ("aaa" "ccc" "bbb") back. Thus the trick of having a copy of the list that is consumed two elements at a time, in order to split the list in the middle.

The next, merge, is the heart of the algorithm and operates by interleaving the elements of two ordered lists in such a way that the combined list is ordered. This process takes only linear (O(n)) time: