Challenge: Bubble Sort, Pass by Pass
Completed
Read a list of numbers and bubble sort it. After every pass print the list (numbers separated by spaces). Stop as soon as a pass makes no swaps (still print that pass).
Input
One line of whole numbers (at least 2).
Output
One line per pass.
Example
Input
5 1 4 2 8
Output
1 4 2 5 8 1 2 4 5 8 1 2 4 5 8
Editor
Python
Hints
The outer loop counts passes; the inner loop compares neighbours.
Print after each pass, then break if nothing was swapped.
Solution explanation
The swapped flag lets bubble sort stop early, so a sorted list takes only one pass.
Show solution
a = list(map(int, input().split()))
n = len(a)
for done in range(n - 1):
swapped = False
for i in range(n - 1 - done):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
swapped = True
print(" ".join(map(str, a)))
if not swapped:
break Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module