def merge_sort(l):
# Exit case: a list with a single element is sorted
if len(l) == 1:
return(l)
# divide the list in 2, sort each list and then merge them (in a way the result is sorted)
return(merge(merge_sort(l[:int(len(l)/2)]), merge_sort(l[int(len(l)/2):])))
def merge(l1, l2):
# l1 and l2 are sorted
l3, i, j = [0 for _ in range(len(l1)+len(l2))], 0, 0
while i < len(l1) or j < len(l2):
# add the smallest between l1[i] and l2[j] and increment its index (beware of size limits)
if i == len(l1) or (j < len(l2) and l1[i] > l2[j]):
l3[i+j] = l2[j]
j += 1
else:
l3[i+j] = l1[i]
i += 1
return(l3)