Search code examples
pythonalgorithmsortingquicksort

Why does multiple variable assigment work for a quick sort algorithm but not for line by line assignment?


Basically trying to understand why doing a multiple variable assignment for a quick sort implementation works, like follows:

if a_list[i] > a_list[i+1]:
    a_list[i], a_list[i+1] = a_list[i+1], a_list[i]

But not doing it line by line, like so:

if a_list[i] > a_list[i+1]:
    a_list[i] = a_list[i+1]
    a_list[i+1] = a_list[i]

Here is the full code if it helps:

def bubble_sort(a_list):
    last_ind = len(a_list) - 1
    flag = True
    
    while flag:
        flag = False
        for i in range(0, last_ind):
            if a_list[i] > a_list[i+1]:
                a_list[i], a_list[i+1] = a_list[i+1], a_list[i]
                flag = True
                
    return a_list
    
    
a_list = [5,8,2,1]
print(bubble_sort(a_list))

Solution

  • In the first implementation, behind the scenes python will create a tuple to store the values of both variables, then will change the values of the variables.

    In the second implementation after the value of a_list[i] is changed, the previous value is lost, so there is no way to set a_list[i+1] to the correct value.