I have this bubbleSort function
in python that works perfectly.
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
I am new to python and I am having trouble understanding the code below the if statement. How does arr[j], arr[j+1] = arr[j], arr[j+1]
work?
If you have come from other programming languages, you might not be familiar with the concept of assigning multiple variables with a single statement.
That is what is happening here.
Ii I x, y = 3, 4
then x will have the value 3 and y will have the value 4
in this case
arr[j], arr[j+1] = arr[j+1], arr[j]
could be rewritten as
arr[j] = arr[j+1]
arr[j+1] = arr[j]
However, that would not swap the variables (which happens in a single statement, as @Dimitar says). It would really need to be rewritten as
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
I hope that you can see why
In Python, tuples can be assigned directly. So the following code
arr[j], arr[j+1] = arr[j+1], arr[j]
if written as this, you would understand it better
(arr[j], arr[j+1]) = (arr[j+1], arr[j])
The code first creates a tuple containing (arr[j+1], arr[j])
, then assign it correspondingly to arr[j], arr[j+1]
, which effectively swaps the two elements.
In other languages, you have to write
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
which is just unnecessary in Python, given that you can assign tuples directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With