I found the following code from geeks for geeks and I don't seem to understand how the sub-arrays are being sorted(i.e. when we sort the left sub-array and then the right sub-array and then, merge both left and right sub-arrays, how come we don't get a wrong answer as the elements sorted in the sub-array merging is the sub-arrays themselves, which according to my understanding are being initialized all the time in the ff code). To better explain my question, I am using an example as following: input_array = [7,1,4,3,5,2,9,8] when we recursively call mergesort, m(7,1,4,3]->m[7,1]->m[7]->m[1]->sort[7,1]-> then we get it sorted to [1,7] and then we proceed to the right half, m[4,3]->m[4]->m[3]->sort[4,3]-> then we get it sorted to [3,4]. what I don't understand is that when we try to sort [7,1,4,3], as we can see in the code below the comparison is made between all the left sub-arrays and all the right sub-arrays and when we do that, the left and right sub-arrays aren't sorted(i am sure I am wrong but in my understanding, the sorted sub-arrays above are already forgotten and discarded from the stack and right after the left and right sub-arrays of [7,1,4,3] are sorted and get discarded the top of the stack is now m[7,1,4,3] and its L is still [7,1] and its R is [4,3] as they weren't updated in the previous sub-array sorting call). I am sure I am missing something here(maybe about pointers, in-place sorting, or how the stack call and related stuff works but I still can't see why?) I have included the code below
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1