Answer the question
In order to leave comments, you need to log in
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)
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)
Answer the question
In order to leave comments, you need to log in
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question