This code is meant to sort a list of integers using merge sort.
I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.
def merge_sort(l):
if len(l) == 0 or len(l) == 1:
return
mid = len(l) // 2
left = l[:mid]
right = l[mid:]
merge_sort(left)
merge_sort(right)
merge(l, left, right)
def merge(l, left, right):
l_ind, r_ind, ind = 0, 0, 0
left_len, right_len, l_len = len(left), len(right), len(l)
while l_ind < left_len and r_ind < right_len:
if left[l_ind] < right[r_ind]:
l[ind] = left[l_ind]
l_ind += 1
ind += 1
else:
l[ind] = right[r_ind]
r_ind += 1
ind += 1
if l_ind < left_len and r_ind >= right_len:
while ind < l_len:
l[ind] = left[l_ind]
l_ind += 1
ind += 1
elif l_ind >= left_len and r_ind < right_len:
while ind < l_len:
l[ind] = right[r_ind]
r_ind += 1
ind += 1