0

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)
Molly
  • 25
  • 7

1 Answers1

1
  • i represents the current position in the left half
  • j represents the current position in the right half
  • k represents the current position in the "merged" array

The first while continues until one of the index (i and j) has passes the length of the respective array.

The 2nd while and 3rd while behave the same - copy the remaining items in the halves into the "merged". One of the halves is already empty.

Increments to k has the same meaning in all 3 whiles you take an element from one of the halves and put it in and move on to the next index.

I'm not sure what's popular these days but on LeetCode there are a bunch of problems tagged with "sort" - many of them should have solutions as well.


Here's some information regarding the return values (not relevant here) and passing by reference or value (relevant):

I'd check out more resources if you are confused about the topic.

nevets1219
  • 7,692
  • 4
  • 32
  • 47