Merge sort

Merge sort is a sorting algorithm invented by John von Neumann based on the divide and conquer technique. It always runs in $$\Theta(n \log n)\,$$ time, but requires $$O(n)\,$$ space. The general concept is that we first break the list into two smaller lists of roughly the same size, and then use merge sort recursively on the subproblems, until they cannot subdivide anymore (i.e. when they contain zero or one elements). Then, we can merge by stepping through the lists in linear time. The recurrence is thus:

$$T(n) = T(\frac{n}{2}) + T(\frac{n}{2}) + \Theta(n)$$

which solves to:

$$T(n) = \Theta(n \log n)\,$$

Pseudo-code
func mergesort( var a as array ) if ( n = 1 ) return a
 * a is a array containing n elements.

var l1 as array = a[0] ... a[n/2] var l2 as array = a[n/2+1] ... a[n]

l1 = mergesort( l1 ) l2 = mergesort( l2 )

return merge( l1, l2 ) end func

func merge( var a as array, var b as array ) var c as array

while ( a and b have elements ) if ( a[0] > b[0] ) add b[0] to the end of c              remove b[0] from b          else add a[0] to the end of c              remove a[0] from a     while ( a has elements ) add a[0] to the end of c         remove a[0] from a     while ( b has elements ) add b[0] to the end of c         remove b[0] from b     return c end func

Bottom-up merge sort
Bottom-up merge sort is a non-recursive variant of the merge sort, in which the array is sorted by a sequence of passes. During each pass, the array is divided into blocks of size $$m\,$$. (Initially, $$m=1\,$$). Every two adjacent blocks are merged (as in normal merge sort), and the next pass is made with a twice larger value of $$m\,$$.

In pseudo-code: Input: array a[] indexed from 0 to n-1.

m = 1 while m <= n do   i = 0 while i < n-m do       merge subarrays a[i..i+m-1] and a[i+m .. min(i+2*m-1,n-1)] in-place. i = i + 2 * m   m = m * 2

Implementations
C++