I understand most of the parts of the implementation of the merge sort. But I am kind of confused about the k = k + 1 under the second and third while loop. I thought the k is going to update to 0 again whatever we do k = k + 1 or not. But the result would be different after I commented the k = k + 1. Could someone explain that to me?
And is there recommendations for me to find some practical sorting problems online(with solutions)?
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1## what is the meaning of k += 1?
# if we don't have k += 1 then the result will be
#Merging [0, 1, 2, 17, 26, 54, 55, 2, 0, 93, 2, 0]
#[0, 1, 2, 17, 26, 54, 55, 2, 0, 93, 2, 0]
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
alist = [54,26,93,17,77,31,44,55,20, 1, 2, 0]
mergeSort(alist)
print(alist)