A
A
alex112352020-08-20 23:50:32
Python
alex11235, 2020-08-20 23:50:32

How does it work (bubble sort optimization)?

Hello. I am learning the basics of Python and in the task of optimizing the bubble sort algorithm, I came across the fact that the code, correct at first glance, produced an incompletely sorted list. Here is the code itself:

a = [3, 2, 4, 1, 9, 6, 5, 7]
swap = True
for i in range(len(a) - 1):   
    if swap == False:
        break
    for j in range(len(a) - i - 1):
        x1, x2 = a[j], a[j + 1]
        if a[j] > a[j + 1]:
            a[j], a[j + 1] = a[j + 1], a[j]            
            swap = True
        else:
            swap = False
print(a)


At random, I found out that in the penultimate line after 'else:' you should leave only False, and remove 'swap ='. It turned out like this:
a = [3, 2, 4, 1, 9, 6, 5, 7]
swap = True
for i in range(len(a) - 1):   
    if swap == False:
        break
    for j in range(len(a) - i - 1):
        x1, x2 = a[j], a[j + 1]
        if a[j] > a[j + 1]:
            a[j], a[j + 1] = a[j + 1], a[j]            
            swap = True
        else:
            False
print(a)

Everything is working. But I don't understand what the difference is. At the 14th step (I look at pythontutor), the correct code after the line if a[j] > a[j + 1]: goes to a new loop, and the wrong one goes to the 12th line and changes the value of the swap variable to False. Actually my question is the following: what is the difference between these two options? At first glance, it seemed to me that after else: it is natural to write swap = False, because we are assigning a new value to a variable, which means that it (the variable) must be specified to the left of the assignment sign, and in fact the program works only without specifying the variable itself there. I know I missed something important, but I can't figure out what.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Aksentiev, 2020-08-21
@Sanasol

Well, in the second option, you killed all the logic associated with swap, i.e. it never becomes false, and accordingly sorts as it should all the way.
And when you stick your incomprehensible swap with a check there, then nothing happens on the next iterations of the first cycle.
It turns out that at the moment when sorting reaches some two numbers that do NOT need to be moved, sorting breaks down about swap = false, and gives out what has been sorted up to this point, and the rest in the order as it was originally.

M
milssky, 2020-08-21
@milssky

It's time to feel the difference between break and continue.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question