This was a basic selection sort alg in python.. I just defined another function to swap the elements Here it does not work-
def swp(a, b):
tmp = a
a = b
b = tmp
def selsor(arr):
n=len(arr)-1
for i in range(n):
j=i+1
m=i
while(j<=n):
if(arr[j]<arr[m]):
m=j
j=j+1
swp(arr[m],arr[i])
but when I make following changes, it works-
def swp(a, b):
tmp = a
a = b
b = tmp
return a,b
def selsor(arr):
n=len(arr)-1
for i in range(n):
j=i+1
m=i
while(j<=n):
if(arr[j]<arr[m]):
m=j
j=j+1
arr[m],arr[i]=swp(arr[m],arr[i])
I just don't understand why the swp() function is not changing the array elements by itself and have to make it return the elements and have to assign it again... For ex. the array itself gets changed as I pass it through the selsor() function. Why can't the swp() also work the same way?