Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bubble Sort in Python [duplicate]

Tags:

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?

like image 793
Kaushani Roy Chowdhury Avatar asked Jan 31 '18 07:01

Kaushani Roy Chowdhury


2 Answers

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

like image 51
Mawg says reinstate Monica Avatar answered Sep 20 '22 13:09

Mawg says reinstate Monica


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.

like image 20
iBug Avatar answered Sep 19 '22 13:09

iBug