Bubble Sort in Python

I have this one bubbleSort functionin python that works fine.

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 it is hard for me to understand the code below the if statement. How does it work arr[j], arr[j+1] = arr[j], arr[j+1]?

+4
source share
4 answers

This is basically just a replacement for arr[j]and arr[j+1]. arr[j]gets the value arr[j+1], but arr[j+1]gets the value arr[j].

+1
source

If you come from other programming languages, you may not be familiar with the concept of assigning multiple variables using a single operator.

Here is what happens here.

II i x, y = 3, 4, then x will have a value of 3, and y will have a value of 4

in this case

arr[j], arr[j+1] = arr[j+1], arr[j] can be rewritten as

arr[j] = arr[j+1]
arr[j+1] = arr[j]

( , @Dimitar).

temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp

, ,

+1

Python . ,

arr[j], arr[j+1] = arr[j+1], arr[j]

,

(arr[j], arr[j+1]) = (arr[j+1], arr[j])

, (arr[j+1], arr[j]), arr[j], arr[j+1], .

temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp

Python, .

+1

: (arr[j], arr[j+1]) = (arr[j+1], arr[j])

:

  • arr[j+1] arr[j] .
  • .
  • arr[j] arr[j+1].

. , , j j+1 of arr.

:

tmp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = tmp
-1
source

Source: https://habr.com/ru/post/1692953/


All Articles