A recursive function to sort a list of ints

The quick sort is recursive and easy to implement in Python:

def quick_sort(l):
    if len(l) <= 1:
        return l
    else:
        return quick_sort([e for e in l[1:] if e <= l[0]]) + [l[0]] +\
            quick_sort([e for e in l[1:] if e > l[0]])

will give:

>>> quick_sort([3, 1, 2, 4, 7, 5, 6, 9, 8])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

For this you would want to use merge sort. Essentially in a merge sort you recursively split the list in half until you have single elements and than build it back up in the correct order. merge sort on has a complexity of O(n log(n)) and is an extremely stable sorting method.

Here are some good in depth explanations and visuals for merge sorting:

  • https://www.youtube.com/watch?v=vxENKlcs2Tw
  • http://www.princeton.edu/~achaney/tmve/wiki100k/docs/Merge_sort.html