My question is relatively simple compared to how I got there. Do recursive functions in Python create a new namespace each time the function calls itself?
I was doing some reading on mergesort and came across this tutorial: https://interactivepython.org/runestone/static/pythonds/SortSearch/TheMergeSort.html#lst-merge
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
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]
mergeSort(alist)
print(alist)
I'm understanding the divide-and-conquer well enough, but what I can't get past at the moment is the question I asked above. I can follow the code, but I'm not quite understanding the use of lefthalf as the argument that gets passed into the recursive function call of mergeSort.
I get that when mergeSort is first called way down at the bottom, alist gets chopped into [54, 26, 93, 17] and [17, 77, 31, 44, 55, 20]. These are lefthalf and righthalf. Then mergeSort gets called on lefthalf. This is where I get confused. Does the recursive call to mergeSort create a whole new namespace, and is that why the lefthalf that gets passed in doesn't collide with the lefthalf defined within the function?
I know the answer to this is really simple and fundamental, so your patience is much appreciated. Thanks in advance!