I wrote a short Merge sort algorithm in Python 3. I have trouble understanding how it manages to achieve the correct result, as when I try to trace its logical steps I end up with an out of order list. The annotated code can be seen below.
What I'm specifically referring to is the merging part of the code. The three 'while' loops.
Let me use an example to demonstrate what confuses me. I explain the details in the annotations.
Thank you in advance for your time and help.
Let's assume we want to merge two arrays.
left = [2,6]
right = [4,8]
def merge_sort(array):
if len(array) > 1:
middle = len(array)//2
left = array[:middle]
right = array[middle:]
merge_sort(left)
merge_sort(right)
i = j = k = 0
while i < len(left) and j < len(right):
# i.e. if 2 < 4
if left[i] < right[j]:
# The first index of the array is assigned the value 2
array[k] = left[i]
# i = 1 now
i += 1
# The 'else' statement is not executed, because the 'if' statement was.
else:
array[k] = right[j]
j += 1
# k = 1 now
k += 1
# The 'while' loop below assigns '6' as the value for index 1 of the array and terminates.
# k = 2 now
while i < len(left):
array[k] = left[i]
i += 1
k += 1
# The last 'while' loop assigns '4' and '8' to indexes 2 and 3 of the array, respectively.
while j < len(right):
array[k] = right[j]
j += 1
k += 1
# The algorithm terminates and from what I can see I should end up with the array of [2,6,4,8].
# I do not, however. It is sorted in ascending order and I cannot see where I'm making a mistake.