This is a source code for Quicksort in Python I found on Wikipedia.
def pivot(v, left, right):
i = left
for j in range(left + 1, right + 1):
if v[j] < v[left]:
i += 1 # .. incrementa-se i
v[i], v[j] = v[j], v[i]
v[i], v[left] = v[left], v[i]
return i
def qsort(v, left, right):
if right > left:
r = pivot(v, left, right)
qsort(v, left, r - 1)
qsort(v, r + 1, right)
a = [4,2,4,6,3,2,5,1,3]
qsort(a, 0, len(a)-1)
print a # prints [1, 2, 2, 3, 3, 4, 4, 5, 6]
My question is about scope. When I pass a as an argument in the example above, how can the function qsort possibly change the variable a in a global scope if it doesn’t “call” ‘global a’? I’ve been programming in python for 1 year and recently started learning C. Looks like I’m making some sort of confusion.
thanks
It doesn’t rebind
a/v, it merely mutates it. You don’t need to declare a nameglobalif you’re mutating the object it’s bound to.