I was studying merge sort and I wrote this code
def mergesort(a): #sorting algo
#code is alright just confused about scope of variable
if(len(a)>1):
mid = len(a)//2
l = a[:mid]
r = a[mid:]
mergesort(l)
mergesort(r)
i=j=k=0
while(i<len(l) and j<len(r)):
if(l[i]>r[j]):
a[k] = r[j]
j+=1
else:
a[k] = l[i]
i+=1
k+=1
while(i<len(l)):
a[k] = l[i]
i+=1
k+=1
while(j<len(r)):
a[k] = r[j]
j+=1
k+=1
a = [30,2,4,5,-1,3,7,3,9,2,5]
mergesort(a)
print(a)
here a
is a global variable, but when the function parameter name is also a
doesn't the a
in function scope override the a
in the global scope? how the global variable is getting edited inside mergesort
function?
I tried another code with same approach but here the global variable doesn't get edited(as expected),how is this different from the above code?
def foo(a):
a=20
a = 10
foo(a)
print(a)