I'm working on understanding and implementing a merge sort. I'm running into a brick wall on this one, and can't seem to get an implementation that works. My current implementation hits a "list index out of range" error. Here is my code:
def merge_sort(list_a):
mid = len(list_a) // 2
print('Mid is ', mid)
while len(list_a) > 1:
left = list_a[:mid]
print('Left is now ', left)
right = list_a[mid:]
print('Right is now ', right)
merge_sort(left)
merge_sort(right)
merge(list_a, left, right)
def merge(comb_list, list_a, list_b):
print('Starting the merge.')
a1, b1, c1 = 0, 0, 0
na, nb, nc = len(list_a), len(list_b), len(comb_list)
while a1 < na and b1 < nb:
if list_a[a1] < list_b[b1]:
print('Adding from A')
comb_list[c1] = list_a[a1]
a1 += 1
else:
print('Adding from B')
comb_list[c1] = list_b[b1]
b1 += 1
c1 += 1
while list_a:
comb_list[c1] = list_a[a1]
c1 += 1
a1 += 1
while list_b:
comb_list[c1] = list_b[b1]
c1 += 1
b1 += 1
if __name__ == '__main__':
list_a = [54,26,93,17,77,31,44,55,20]
merge_sort(list_a)
while list_a:meanswhile len(list_a) != 0:. You don't modify yourlist_ainside while block, so this cycle is interminable, variablea1grows and go out of list length.