Python Algorithms

Bubble Sort in Python

Watch the largest value bubble to the end on every pass, and stop early once the list is sorted.

  • Intermediate
  • 2 min read
  • 1 runnable example
What you'll learn
  • Comparing and swapping neighbors
  • Why each pass fixes one more value
  • The early-exit swapped flag
Passes over [5, 1, 4, 2, 8]
5
1
4
2
8
1
4
2
5
8
1
2
4
5
8
The third pass makes no swap, so the loop ends early.

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.

From lining up children to code
result[index] > result[index + 1]👫 Is the taller child in front?
result[index], result[index + 1] = ...🔄 Swap the two neighbors
for end in range(len(result) - 1, 0, -1):🚶 Walk the line again, one child shorter each time
if not swapped: break✅ No swaps in a whole walk: the line is sorted
After each pass, the largest remaining value is in its final place.
In one sentence

Bubble 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

  1. result = values.copy() sorts a copy, so the caller's list is not changed.
  2. if result[index] > result[index + 1]: swaps a pair that is in the wrong order.
  3. end shrinks after every pass, because the largest values are already at the end.
  4. if not swapped: break stops 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() and list.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

Run code →
main.py
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]))
Get a Run button for this example

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.

  1. Try empty, single-item, and duplicate-value inputs.
  2. Print state after every step to observe the algorithm.
  3. Benchmark 100, 1,000, and 10,000 items, then compare another approach.
Run in the Python compiler →

Common mistakes

Going one index too far

result[index + 1] goes past the end when index reaches the last position.

Problem
for index in range(len(result)):
    if result[index] > result[index + 1]:
Fix
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.

All challenges