merge sorty code example
Example: merge sort
# Python3 recursive merge sort algorithm -> O(n*log(n))
def merge_sort(A):
def merge(l, r):
i = j = 0
n = [] # merging container
while i < len(l) or j < len(r):
# if no more elements to the right,
# add remaining left elements
if i == len(l):
n.extend(r[j:])
break
# if no more elements to the left,
# add remaining right elements
if j == len(r):
n.extend(l[i:])
break
# if elements left on both sides,
# add smaller element
a, b = l[i], r[j]
if a < b:
n.append(a)
i += 1
else:
n.append(b)
j += 1
return n
# divide list down to single-elements
s = len(A)
if s > 1:
s
l = merge_sort(A[:s]) # split left
r = merge_sort(A[s:]) # split right
return merge(l, r) # merge sides in order
else:
return A