Reputation: 35
The Code:
def selection(list, i, j, flag, swapNumber):
size = len(list)
if (i < size - 1):
if (flag):
j = i + 1;
print(list)
if (j < size):
if (list[i] > list[j]):
swapNumber +=1
print(swapNumber)
list[i],list[j]=list[j],list[i]
print(list)
selection(list, i, j + 1, 0, swapNumber);
else:
selection(list, i + 1, i+2, 1, swapNumber);
return(swapNumber)
swapNumber = 0
list = [6, 2, 3, 7, 1]
numSwap = selection(list, 0, 1, 1, swapNumber)
print(list)
print(numSwap)
So I'm trying to return the value of the swapNumber but when it prints it just says 1. I tried placing the return(swapNumber) somewhere else didn't seem to help. Anyone can help with this?
Upvotes: 0
Views: 133
Reputation: 1648
One cheecky way would be to define a function inside of a function and use nonlocal
. Would look like this:
def selection_sort(list_):
swaps = 0
def selection(list_, i, j, flag):
nonlocal swaps
size = len(list_)
if i < size - 1:
if flag:
j = i + 1
if j < size:
if list_[i] > list_[j]:
swaps += 1
list_[i], list_[j] = list_[j], list_[i]
selection(list_, i, j + 1, 0)
else:
selection(list_, i + 1, i + 2, 1)
return swaps
return selection(_list, 0, 1, 1)
The benefit is also the fact that you don't need to pass 0, 1, 1
as initial params, just the list to be sorted itself.
Upvotes: 1
Reputation: 1804
The swapNumber
passed to function selection
is by value
other than by reference
.
One possible solution is declare it to be global
:
def selection(list, i, j, flag):
global swapNumber
size = len(list)
if (i < size - 1):
if (flag):
j = i + 1;
print(list)
if (j < size):
if (list[i] > list[j]):
swapNumber +=1
print(swapNumber)
list[i],list[j]=list[j],list[i]
print(list)
swapNumber = selection(list, i, j + 1, 0);
else:
swapNumber = selection(list, i + 1, i+2, 1);
return(swapNumber)
swapNumber = 0
list = [6, 2, 3, 7, 1]
numSwap = selection(list, 0, 1, 1)
print(list)
print(numSwap)
Upvotes: 1