Reputation: 390
I'm trying to make a bubble sort method for python just for poops and grins. I don't think my swap method is working though.
def bubbleSort(list):
length = len(list)
for i in range(length - 1):
if list[i] > list[i+1]:
#swap
swap(list[i], list[i+1])
print(list)
print(list)
def swap(s1, s2):
# assert type(s1) == list and type(s2) == list
# tmp = s1[:]
# s1[:] = s2
# s2[:] = tmp
s2, s1 = s1, s2
The program spits out my list, but nothing changes any of the times which tells me that my swap method isnt working.
Upvotes: 0
Views: 1616
Reputation: 41232
If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like call-by-value. The object reference is passed to the function parameters. They can't be changed within the function, because they can't be changed at all, i.e. they are immutable. It's different, if we pass mutable arguments. They are also passed by object reference, but they can be changed in place in the function. If we pass a list to a function, we have to consider two cases: Elements of a list can be changed in place, i.e. the list will be changed even in the caller's scope. If a new list is assigned to the name, the old list will not be affected, i.e. the list in the caller's scope will remain untouched.
Strictly speaking in your examples passing elements of list into swap
function, won't have effect. While having python syntax allowing you to write this directly:
list[i], list[i+1] = list[i+1], list[i]
not sure what is the purpose of extracting such tiny logic into separate function.
PS. To read more about evaluation strategies, e.g. call-by-value, call-by-reference and why it's different, you can take a look in wiki.
PPS. As correctly noted in the comment, the common evaluation strategy for python is "Call-by-Sharing", e.g.:
Call by sharing (also referred to as call by object or call by object-sharing) is an evaluation strategy first named by Barbara Liskov et al. for the language CLU in 1974.[5] It is used by languages such as Python,[6] Iota,[7] Java (for object references), Ruby, JavaScript, Scheme, OCaml, AppleScript, and many others. However, the term "call by sharing" is not in common use; the terminology is inconsistent across different sources. For example, in the Java community, they say that Java is call by value.[8] Call by sharing implies that values in the language are based on objects rather than primitive types, i.e. that all values are "boxed".
Upvotes: 4