This video explains the merge-sort algorithm really well, and it does so in 3 minutes! The second half of the video is a race between merge-sort and quick-sort and I'm surprised how well it highlights the intricacies.

GIF animation

Algorithm

define mergesort(x):

recursively sort first-half of x

recursively sort second-half of x

merge sorted halfs into single sorted array

Analysis

The easiest way to understand the run-time complexity of merge-sort is to look at the recursion graph. There are O(log n) layers in the tree, and each layer is size O(n). Hence, the total algorithm is O(n log n). Its at-least as important to understand this intuitively as it is to understand it rigorously.

Code (almost python)

define mergesort(x):

""" Sort array using merge sort algorithm """

# base case

if length(x) <= 1: return x

# split from middle. mergesort each half. then merge

middle = length(x)/2

a = mergesort(x[:middle])

b = mergesort(x[middle:])

return merge(a, b)

define merge(a, b):

""" merge arrays a and b """

c = list()

while not empty(a) or not empty(b):

# add smaller element to c and remove from original array

# (handle boundary cases of a / b being empty)

if empty(a) or (not empty(b) and a[0] <= b[0]):

c.append(a[0])

a.pop()

else:

c.append(b[0])

b.pop()

return c

Other notes

You can also read a text description of the algorithm on IARCS Online Study Material. For a bonus video, a classic exercise on merge-sort, and more information, check out the responses to this discussion.