Python bubble sort
Move the largest remaining item to the end with adjacent swaps.
On this page
Nested loops and tuple assignment.
- Move the largest remaining item to the end with adjacent swaps.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
Each pass compares neighboring values and swaps an inverted pair. After a full pass, the largest value in the unsorted prefix is in its final position.
A swapped flag allows early exit when a pass makes no changes. Strict comparison keeps equal elements in their original relative order.
Code example
def bubble_sort(values):
result = values.copy()
for end in range(len(result) - 1, 0, -1):
swapped = False
for i in range(end):
if result[i] > result[i + 1]:
result[i], result[i + 1] = result[i + 1], result[i]
swapped = True
if not swapped:
break
return result
print(bubble_sort([3, 2, 1]))
assert bubble_sort([]) == []
assert bubble_sort([1, 1, 2]) == [1, 1, 2][1, 2, 3]
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
def bubble_sort(values): result = values.copy() for end in range(len(result) - 1, 0, -1): swapped = False for i in range(end): if result[i] > result[i + 1]: result[i], result[i + 1] = result[i + 1], result[i] swapped = True if not swapped: break return result print(bubble_sort([3, 2, 1]))assert bubble_sort([]) == []assert bubble_sort([1, 1, 2]) == [1, 1, 2]Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Copy the input. | result = [3, 2, 1] | — | |
| First pass swaps 3 and 2. | result = [2, 3, 1] | — | |
| Then swap 3 and 1; the largest item is placed. | result = [2, 1, 3] | — | |
| Second pass swaps 2 and 1. | result = [1, 2, 3] | — | |
| Return and print the copy. | result = [1, 2, 3] | [1, 2, 3] |
Behind the scenes
How Python processes this code
Python runs this source through its interpreter. It creates objects for values and resolves names as each statement runs.
Cost and common mistakes
O(n²) worst-case time, O(n) best-case time with early exit; O(n) auxiliary space for this copying version.
- The inner loop stops before end so i+1 remains valid.
- Bubble sort is mainly educational; built-in sorting is preferable for ordinary use.
Try it yourself
Trace [1, 2, 3].
Reveal answer and reasoning
The first pass makes no swaps and exits early, returning the unchanged order.