ZetCode

Python bubble sort

last modified November 18, 2026 Python 3.15

In this article we explain the bubble sort algorithm in Python. We implement it, trace its passes, optimize it, use it with key functions, and compare it with the built-in sorted function.

Sorting arranges data in a specific order, such as ascending or descending. In real Python code we use list.sort or sorted, which implement a highly tuned hybrid algorithm (Timsort, and Powersort merging since Python 3.11). Simple algorithms such as bubble sort are studied because they show the basic ideas of comparing and swapping elements, of loop invariants, and of algorithm complexity.

Bubble sort algorithm

Bubble sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. After the first pass, the largest element has "bubbled up" to the end of the list. After the second pass, the second largest element is in its final position, and so on. Each pass can therefore stop one element earlier than the previous one.

PropertyValue
Best case timeO(n) with the early-exit optimization, otherwise O(n2)
Average case timeO(n2)
Worst case timeO(n2)
Extra spaceO(1), sorts in place
Stableyes

A sort is stable when elements with equal keys keep their original relative order. Stability matters when we sort records by one field after they have been sorted by another.

Bubble sort example

The following is a basic implementation of bubble sort.

bubble_sort.py
def bubble_sort(vals):
    n = len(vals)
    for i in range(n - 1):
        for j in range(n - 1 - i):
            if vals[j] > vals[j + 1]:
                vals[j], vals[j + 1] = vals[j + 1], vals[j]


nums = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(nums)
print(nums)

The outer loop counts the passes; a list of n elements needs at most n - 1 of them. The inner loop compares neighbours and swaps them with tuple assignment. Since the last i elements are already in place, the inner loop runs only up to n - 1 - i. The function sorts the list in place and returns None, like list.sort.

$ python bubble_sort.py
[11, 12, 22, 25, 34, 64, 90]

Tracing the passes

To see how the algorithm works, we print the list after each pass.

bubble_trace.py
def bubble_sort(vals):
    n = len(vals)
    for i in range(n - 1):
        for j in range(n - 1 - i):
            if vals[j] > vals[j + 1]:
                vals[j], vals[j + 1] = vals[j + 1], vals[j]
        print(f'pass {i + 1}: {vals[:n - 1 - i]} | {vals[n - 1 - i:]}')


nums = [5, 1, 4, 2, 8, 3]
print('start: ', nums)
bubble_sort(nums)

The vertical bar separates the unsorted part from the sorted tail. After each pass the largest element of the unsorted part moves to the start of the tail. The tail grows by one element per pass.

$ python bubble_trace.py
start:  [5, 1, 4, 2, 8, 3]
pass 1: [1, 4, 2, 5, 3] | [8]
pass 2: [1, 2, 4, 3] | [5, 8]
pass 3: [1, 2, 3] | [4, 5, 8]
pass 4: [1, 2] | [3, 4, 5, 8]
pass 5: [1] | [2, 3, 4, 5, 8]

Stopping early

If a pass makes no swap, the list is sorted and the remaining passes can be skipped. This optimization makes bubble sort adaptive: on an already sorted list it finishes after a single pass, which is O(n).

early_exit.py
def bubble_sort(vals):
    n = len(vals)
    passes = 0
    for i in range(n - 1):
        passes += 1
        swapped = False
        for j in range(n - 1 - i):
            if vals[j] > vals[j + 1]:
                vals[j], vals[j + 1] = vals[j + 1], vals[j]
                swapped = True
        if not swapped:
            break
    return passes


data = {
    'sorted': list(range(1, 11)),
    'one swap': [1, 2, 3, 4, 6, 5, 7, 8, 9, 10],
    'reversed': list(range(10, 0, -1)),
}

for name, vals in data.items():
    passes = bubble_sort(vals)
    print(f'{name:>8}: {passes} passes -> {vals}')

The swapped flag records whether the inner loop changed anything. The function returns the number of passes it performed.

$ python early_exit.py
  sorted: 1 passes -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
one swap: 2 passes -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
reversed: 9 passes -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Counting comparisons

Comparisons dominate the running time of bubble sort. In this example we count them for three variants: the plain algorithm, the early exit, and a variant that remembers the position of the last swap.

comparisons.py
import random


def plain(vals):
    count = 0
    n = len(vals)
    for i in range(n - 1):
        for j in range(n - 1 - i):
            count += 1
            if vals[j] > vals[j + 1]:
                vals[j], vals[j + 1] = vals[j + 1], vals[j]
    return count


def early_exit(vals):
    count = 0
    n = len(vals)
    for i in range(n - 1):
        swapped = False
        for j in range(n - 1 - i):
            count += 1
            if vals[j] > vals[j + 1]:
                vals[j], vals[j + 1] = vals[j + 1], vals[j]
                swapped = True
        if not swapped:
            break
    return count


def last_swap(vals):
    count = 0
    end = len(vals) - 1
    while end > 0:
        last = 0
        for j in range(end):
            count += 1
            if vals[j] > vals[j + 1]:
                vals[j], vals[j + 1] = vals[j + 1], vals[j]
                last = j
        end = last
    return count


rng = random.Random(1)
n = 100
inputs = {
    'sorted': list(range(n)),
    'nearly sorted': list(range(n)),
    'random': rng.sample(range(n), n),
    'reversed': list(range(n, 0, -1)),
}
nearly = inputs['nearly sorted']
nearly[10], nearly[90] = nearly[90], nearly[10]

print(f'{"input":<14}{"plain":>8}{"early exit":>12}{"last swap":>11}')
for name, vals in inputs.items():
    counts = [f(vals.copy()) for f in (plain, early_exit, last_swap)]
    print(f'{name:<14}{counts[0]:>8}{counts[1]:>12}{counts[2]:>11}')

Everything behind the last swap of a pass is already sorted, so last_swap uses that position as the end of the next pass. It can skip several elements per pass instead of one. The nearly sorted list has two elements swapped: the large one moves to its place in a single pass, but the small one moves only one position to the left per pass. Such small elements near the end are called turtles; they keep bubble sort slow even on almost sorted data. The reversed list is the worst case; no optimization helps there.

$ python comparisons.py
input            plain  early exit  last swap
sorted            4950          99         99
nearly sorted     4950        4779       4059
random            4950        4922       4787
reversed          4950        4950       4950

Key functions and descending order

Built-in sorting accepts the key and reverse parameters. We can add them to our function too.

bubble_key.py
def bubble_sort(vals, key=None, reverse=False):
    if key is None:
        key = lambda e: e
    n = len(vals)
    for i in range(n - 1):
        swapped = False
        for j in range(n - 1 - i):
            a, b = key(vals[j]), key(vals[j + 1])
            if (b > a) if reverse else (a > b):
                vals[j], vals[j + 1] = vals[j + 1], vals[j]
                swapped = True
        if not swapped:
            break


words = ['banana', 'Cherry', 'apple', 'date', 'Elderberry', 'fig']

bubble_sort(words)
print(words)

bubble_sort(words, key=str.lower)
print(words)

bubble_sort(words, key=len, reverse=True)
print(words)

The key function is applied to both elements before they are compared. With reverse=True we swap when the right element is greater. Without a key, uppercase letters sort before lowercase ones because strings are compared by code points; str.lower gives a case-insensitive order. In the last call, banana and Cherry have the same length and keep their previous order, because the sort is stable.

$ python bubble_key.py
['Cherry', 'Elderberry', 'apple', 'banana', 'date', 'fig']
['apple', 'banana', 'Cherry', 'date', 'Elderberry', 'fig']
['Elderberry', 'banana', 'Cherry', 'apple', 'date', 'fig']

Stability

Bubble sort is stable only if it swaps on a strict comparison. Swapping equal elements breaks the stability.

bubble_stable.py
from dataclasses import dataclass


@dataclass
class Student:
    name: str
    grade: str


def bubble_sort(vals, key, strict=True):
    n = len(vals)
    for i in range(n - 1):
        for j in range(n - 1 - i):
            a, b = key(vals[j]), key(vals[j + 1])
            if a > b if strict else a >= b:
                vals[j], vals[j + 1] = vals[j + 1], vals[j]


students = [
    Student('Paul', 'B'), Student('Anna', 'A'), Student('Lucy', 'B'),
    Student('Peter', 'C'), Student('Robert', 'A'), Student('Jane', 'B'),
]

by_grade = students.copy()
bubble_sort(by_grade, key=lambda s: s.grade)
print('stable:  ', [f'{s.name}/{s.grade}' for s in by_grade])

by_grade = students.copy()
bubble_sort(by_grade, key=lambda s: s.grade, strict=False)
print('unstable:', [f'{s.name}/{s.grade}' for s in by_grade])

We sort students by grade. With >, students with the same grade stay in the original order: Paul, Lucy, Jane. With >=, equal elements are swapped as well and the order of the B students changes. Both results are sorted by grade, but only the first one is stable.

$ python bubble_stable.py
stable:   ['Anna/A', 'Robert/A', 'Paul/B', 'Lucy/B', 'Jane/B', 'Peter/C']
unstable: ['Anna/A', 'Robert/A', 'Jane/B', 'Paul/B', 'Lucy/B', 'Peter/C']

Cocktail shaker sort

Cocktail shaker sort is a bidirectional bubble sort. It alternates forward passes, which move large elements to the end, with backward passes, which move small elements to the front. This handles turtles much better.

cocktail_sort.py
def bubble_sort(vals):
    passes = 0
    n = len(vals)
    for i in range(n - 1):
        passes += 1
        swapped = False
        for j in range(n - 1 - i):
            if vals[j] > vals[j + 1]:
                vals[j], vals[j + 1] = vals[j + 1], vals[j]
                swapped = True
        if not swapped:
            break
    return passes


def cocktail_sort(vals):
    passes = 0
    lo, hi = 0, len(vals) - 1
    swapped = True
    while swapped and lo < hi:
        swapped = False
        passes += 1
        for j in range(lo, hi):
            if vals[j] > vals[j + 1]:
                vals[j], vals[j + 1] = vals[j + 1], vals[j]
                swapped = True
        hi -= 1
        for j in range(hi, lo, -1):
            if vals[j - 1] > vals[j]:
                vals[j - 1], vals[j] = vals[j], vals[j - 1]
                swapped = True
        lo += 1
    return passes


turtle = [2, 3, 4, 5, 6, 7, 8, 9, 1]

a, b = turtle.copy(), turtle.copy()
print('bubble sort passes:  ', bubble_sort(a), a)
print('cocktail sort passes:', cocktail_sort(b), b)

The list has a single turtle, 1, at the end. Bubble sort moves it one position per pass and needs eight passes. Cocktail sort carries it to the front in the first backward pass and confirms the order in the second round. The asymptotic complexity is still O(n2).

$ python cocktail_sort.py
bubble sort passes:   8 [1, 2, 3, 4, 5, 6, 7, 8, 9]
cocktail sort passes: 2 [1, 2, 3, 4, 5, 6, 7, 8, 9]

Checking the implementation

A good way to test a sorting function is to compare its results with sorted on many random inputs, together with edge cases.

check_sort.py
import random


def bubble_sort(vals):
    n = len(vals)
    for i in range(n - 1):
        swapped = False
        for j in range(n - 1 - i):
            if vals[j] > vals[j + 1]:
                vals[j], vals[j + 1] = vals[j + 1], vals[j]
                swapped = True
        if not swapped:
            break


rng = random.Random(42)
cases = [[], [1], [2, 1], [3, 3, 3], [-1, 0, -5, 2.5]]
cases += [[rng.randint(-50, 50) for _ in range(rng.randint(0, 40))]
          for _ in range(1000)]

for case in cases:
    expected = sorted(case)
    bubble_sort(case)
    assert case == expected, case

print(f'{len(cases)} lists sorted correctly')

We test an empty list, single-element lists, duplicates, negative numbers, and floats, and then a thousand random lists of random lengths. The seeded random.Random instance makes the test reproducible.

$ python check_sort.py
1005 lists sorted correctly

Benchmark

Finally, we measure how bubble sort compares with the built-in sorted function.

benchmark.py
import random
import timeit


def bubble_sort(vals):
    n = len(vals)
    for i in range(n - 1):
        swapped = False
        for j in range(n - 1 - i):
            if vals[j] > vals[j + 1]:
                vals[j], vals[j + 1] = vals[j + 1], vals[j]
                swapped = True
        if not swapped:
            break


rng = random.Random(7)

for n in (500, 1000, 2000):
    data = [rng.randint(0, 10_000) for _ in range(n)]
    t_bubble = timeit.timeit(lambda: bubble_sort(data.copy()), number=3) / 3
    t_sorted = timeit.timeit(lambda: sorted(data), number=3) / 3
    print(f'n={n:>5}  bubble sort {t_bubble:9.5f} s'
          f'  sorted {t_sorted:9.6f} s  ratio {t_bubble / t_sorted:7.0f}x')

The timeit function runs each sort three times; we sort a copy so that every run gets unsorted data. Doubling the input size roughly quadruples the bubble sort time, as expected from an O(n2) algorithm, while sorted grows as O(n log n) and runs in C. The times depend on the machine and vary between runs.

$ python benchmark.py
n=  500  bubble sort   0.00517 s  sorted  0.000029 s  ratio     176x
n= 1000  bubble sort   0.02015 s  sorted  0.000080 s  ratio     251x
n= 2000  bubble sort   0.08505 s  sorted  0.000162 s  ratio     525x

Source

Sorting Techniques – Python documentation

timeit – Python documentation

In this article we have implemented and optimized bubble sort in Python. See also Python insertion sort, Python selection sort, Python quick sort, and Python sort list.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.