- This topic is empty.
-
AuthorPosts
-
April 21, 2026 at 5:05 am #6430
When learning algorithms, these two lines may look small—but they control the entire Bubble Sort process:
while did_swap: did_swap = FalseHow do these lines know when to continue sorting and when to stop?
Short Answer
Because
did_swapacts like a signal.If a swap happens during the pass, keep looping.
If no swap happens, stop.
What Is Bubble Sort?
Bubble Sort compares neighboring values and swaps them if they are in the wrong order.
Example:
[8, 4, 1, 6]Becomes:
[1, 4, 6, 8]It is called Bubble Sort because larger values “bubble” to the end after each pass.
Understanding the Two Lines
while did_swap: did_swap = FalseLine 1:
while did_swap:Means:
Continue looping while
did_swapisTrue.If it becomes
False, sorting stops.Line 2:
did_swap = FalseAt the start of every pass, Python assumes:
Maybe the list is already sorted now.
If any swap happens later, it changes back to:
did_swap = True
Step-by-Step Example
Start list:
[3, 2, 1]First Pass
Reset:
did_swap = FalseCompare values:
3 > 2 → swap 3 > 1 → swapList becomes:
[2, 1, 3]Since swaps happened:
did_swap = TrueLoop continues.
Second Pass
Reset:
did_swap = FalseCompare:
2 > 1 → swapList becomes:
[1, 2, 3]Again, swap happened.
Third Pass
Reset:
did_swap = FalseCompare:
1 < 2 2 < 3No swaps happen.
So
did_swapremainsFalse.Loop stops.
Why This Is Smart
Without this logic, Bubble Sort might continue checking even after the list is already sorted.
This saves unnecessary work.
Full Bubble Sort Code
def bubble_sort(L): did_swap = True while did_swap: did_swap = False for j in range(1, len(L)): if L[j - 1] > L[j]: L[j], L[j - 1] = L[j - 1], L[j] did_swap = True return L
Business Analogy
Imagine a manager arranging invoices by date.
Each round:
- Compare neighboring invoices
- Swap if out of order
- If a full round has no movement, stop
That is Bubble Sort logic.
One-Line Takeaway
while did_swap:means keep sorting until one full pass finishes with zero swaps. -
AuthorPosts
- You must be logged in to reply to this topic.
