Bubble Sort in Python
Watch the largest value bubble to the end on every pass, and stop early once the list is sorted.
- Comparing and swapping neighbors
- Why each pass fixes one more value
- The early-exit swapped flag
One pass at a time
The problem
Sorting is everywhere, and understanding how it works helps you reason about speed. Bubble sort is the easiest sorting algorithm to follow step by step, which makes it the usual first example, even though real programs use faster ones.
Think of it like this
Bubble sort is like lining up children by height by only ever swapping two neighbors. Walk down the line and swap any pair where the taller child is in front. After one walk the tallest child has reached the end, like a bubble rising to the surface. Repeat until a walk needs no swaps.
result[index] > result[index + 1]👫 Is the taller child in front?result[index], result[index + 1] = ...🔄 Swap the two neighborsfor end in range(len(result) - 1, 0, -1):🚶 Walk the line again, one child shorter each timeif not swapped: break✅ No swaps in a whole walk: the line is sortedBubble sort repeatedly walks through the list, swapping neighboring items that are in the wrong order, until a full pass makes no swaps; it takes O(n²) time in general.
Key points
result = values.copy()sorts a copy, so the caller's list is not changed.if result[index] > result[index + 1]:swaps a pair that is in the wrong order.endshrinks after every pass, because the largest values are already at the end.if not swapped: breakstops early when a pass makes no swaps, so sorted input finishes after one pass.
When should you use it?
- Learning how comparison-based sorting works.
- Tiny lists in teaching tools and visualizations.
- Checking whether a list is already sorted in one pass.
When not to use it
- Any real program:
sorted()andlist.sort()are far faster (O(n log n)) and tested. - Lists of more than a few hundred items: the number of comparisons grows with the square of the length.
Bubble Sort in Python visualizer
O(n²)Use Play or Step to follow each comparison and data movement.
Example code
def bubble_sort(values):
result = values.copy()
for end in range(len(result) - 1, 0, -1):
swapped = False
for index in range(end):
if result[index] > result[index + 1]:
result[index], result[index + 1] = result[index + 1], result[index]
swapped = True
if not swapped:
break
return result
print(bubble_sort([5, 1, 4, 2, 8]))
Result of running the code
[1, 2, 4, 5, 8]
Code explanation
After every pass, the largest unsorted value reaches its final position. The swapped flag stops early when the list is already sorted. Worst-case time complexity is O(n²).
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Try empty, single-item, and duplicate-value inputs.
- Print state after every step to observe the algorithm.
- Benchmark 100, 1,000, and 10,000 items, then compare another approach.
Common mistakes
Going one index too far
result[index + 1] goes past the end when index reaches the last position.
for index in range(len(result)):
if result[index] > result[index + 1]:
for index in range(end):
if result[index] > result[index + 1]:
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Count Inversions Count the out-of-order pairs in a list. Hard
- Median of a List Find the middle value of a list after sorting. Easy