Merge sort

Merge sort is a sorting algorithm that runs in worst-case $$O(n \log n)$$ time, the lower bound, but requires $$O(n)$$ space to merge. 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 (containing one element.) Then, we can merge by stepping through the lists in linear time. The recurrence is thus:

$$T(n) = T(n/2) + T(n/2) + O(n)$$

which solves to:

$$T(n) = O(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