Full Byte Developer.

Bubble sort Python code you can run

Run bubble sort Python code, try custom values, and inspect its neighbor-swap algorithm.

Published here , updated · 3 sources

Bubble sort compares each pair of neighbors and swaps them when they are out of order, repeating until a pass makes no swaps [3]. It is slow for large inputs and still the clearest adjacent-swap demo. ALGO ARCADE ships a runnable level of the same algorithm [1][2].

One minute: sort four numbers

Save this as bubble_sort.py and run it with Python 3:

python
def bubble_sort(values):
    a = list(values)
    n = len(a)
    passes = 0
    swaps = 0
    for i in range(n):
        swapped = False
        for j in range(0, n - i - 1):
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
                swaps += 1
                swapped = True
        passes += 1
        if not swapped:
            break
    return a, passes, swaps

nums = [5, 3, 8, 1]
print('input:', nums)
print('sorted:', *bubble_sort(nums))
bash
python3 bubble_sort.py

Captured output on this machine:

text
input: [5, 3, 8, 1]
sorted: ([1, 3, 5, 8], 4, 4)

Four passes, four swaps, final order [1, 3, 5, 8]. The early-exit flag did not fire because the last pass still had work until the end of the recorded run; the important part is that every swap only touched neighbors.

Watch one pass as a diagram

Start: 5 3 8 1

Pass 1 neighbor checks:

  1. 5 vs 3 -> swap -> 3 5 8 1
  2. 5 vs 8 -> keep
  3. 8 vs 1 -> swap -> 3 5 1 8

The largest value (8) has bubbled to the end. Later passes shrink the unsorted prefix by one each time because the tail is already finished [3].

pass 1: compare neighbors left to right 5 3 8 1 5>3 swap 5<8 keep 8>1 swap 3 5 1 8 largest at right; next pass stops at n-i-1 sorted tail grows from the right; unsorted prefix shrinks each pass [3]

One left-to-right pass swaps out-of-order neighbors; the max value reaches the right edge before pass 2.

Why the inner loop shrinks

After pass i, the last i positions hold the largest i values in order. The inner loop therefore runs only to n - i - 1. Without that shrink you still get a correct sort, but you re-compare pairs that cannot be wrong anymore [3].

Worst case input is reverse sorted: every comparison can swap. Best case with the swapped flag is already sorted: one pass, zero swaps, then break. That flag is the difference between "always n passes" and "stop when quiet."

Run the ALGO ARCADE level

If you want the packaged level instead of the snippet above [1][2]:

bash
git clone https://github.com/kamilikamil/algo-arcade.git
cd algo-arcade
python3 bubble_sort.py
python3 bubble_sort.py 5 3 8 1

The README documents the CLI and the neighboring sort levels [1]. Use the level when you want the same algorithm with the arcade framing; use the snippet when you want a file you can drop into a kata repo.

Compare the family without mixing claims

Selection sort finds a minimum and places it. Insertion sort grows a sorted prefix by inserting the next value. Bubble sort only swaps neighbors. All three are fine teaching tools. None of them replace Timsort (list.sort in CPython) for real data sizes. When an interviewer asks for bubble sort, they are usually checking whether you can narrate the adjacent invariant, not whether you would ship it.

Mistakes that show up in homework and interviews

  • Skipping the early-exit flag while still calling the algorithm adaptive. Without swapped, a sorted list pays for every pass.
  • Off-by-one in the inner bound (range(n) instead of range(n - i - 1)), which either skips the last needed compare or reads past the list.
  • Mutating the caller's list in place without documenting it. The snippet copies with list(values) so the original nums print stays unchanged; the ALGO ARCADE source may differ, so read the file you run [2].
  • Claiming O(n log n) because four numbers sorted quickly. Asymptotics describe growth with n, not one tiny sample [3].

Instrument the loop once

Add prints inside the inner compare if you are teaching someone else:

python
def bubble_sort_trace(values):
    a = list(values)
    n = len(a)
    for i in range(n):
        swapped = False
        for j in range(0, n - i - 1):
            left, right = a[j], a[j + 1]
            if left > right:
                a[j], a[j + 1] = right, left
                swapped = True
                print(f'pass {i} swap {left}>{right} -> {a}')
            else:
                print(f'pass {i} keep {left}<={right}')
        if not swapped:
            print(f'pass {i} quiet; stop')
            break
    return a

print(bubble_sort_trace([5, 3, 8, 1]))

Save as bubble_trace.py and run python3 bubble_trace.py. For [5, 3, 8, 1] you should see four swaps, matching the counter above. The trace makes each adjacent decision visible, which is why bubble sort still belongs in teaching rooms, not in production sorts [3].

Finish every pass on the same input

Pass 1 ended at 3 5 1 8. Continue with the same rules so the whole sort is on the page:

  • Pass 2: 3 vs 5 keep; 5 vs 1 swap -> 3 1 5 8. The second-largest value (5) settles one slot left of the end. Inner loop stops before the already-sorted 8.
  • Pass 3: 3 vs 1 swap -> 1 3 5 8; 3 vs 5 keep. Sorted prefix from the right is now three cells.
  • Pass 4: 1 vs 3 keep. No swaps, so swapped stays false and the outer loop breaks even if n would allow another pass.

That walkthrough matches the printed counters: four passes, four swaps, result [1, 3, 5, 8]. If your homework asks for "show one full run," this is the level of detail graders want: each neighbor decision, not only the final array [3].

Complexity in plain numbers

Comparisons in the worst case (reverse sorted, no helpful early exit) follow roughly n(n-1)/2. For n = 4 that is at most six compares across the shrinking windows; for n = 100 it is about 4950 compares; for n = 1000 about half a million. Memory beyond the input is constant (a few integers and a boolean) unless you copy the list first as the snippet does. Average and worst case stay quadratic; best case with early exit is linear on an already sorted list [3].

Those numbers are why CPython's list.sort (Timsort) is the default for real data. Bubble sort earns its keep when the goal is to see an invariant ("after pass i, the last i cells are final") with your eyes.

Stability and equal keys

Classic bubble sort that only swaps on > (not >=) leaves equal keys in their original relative order, so it is stable [3]. That property matters when you sort records by one field and want ties to keep an earlier secondary order. Interview answers that say "all quadratic sorts are interchangeable" miss that distinction.

Try [2a, 1, 2b] where 2a and 2b compare equal on the sort key. After bubble sort with a strict > swap, 2a should still sit left of 2b. Swap on >= and you can reorder equals for no benefit.

Nearly sorted inputs

Early exit is most useful when the list is already sorted or only a few adjacent pairs are wrong. A single inversion such as [1, 2, 4, 3, 5] may finish in two passes: one pass swaps 4 and 3, the next pass finds quiet and breaks. The same input without the swapped flag still walks every remaining pass. When someone says bubble sort is "good for nearly sorted data," they are talking about that flag, not about the bare nested loops [3].

What to try next

Print passes and swaps for [1, 2, 3, 4] and for [4, 3, 2, 1] on the same function. The gap between those two rows is the whole lesson. Then open BFS or binary search when you want a different complexity story on the same site.

Send this to the friend who memorized bubble sort and never watched one pass finish.

A row of uneven amber bars where neighboring pairs swap with small teal arcs, and after each pass the rightmost sorted region becomes still and slightly brighter as the remaining unsorted window shrinks from the right, with no typography or numerals.
Each pass swaps neighbors and leaves one more value in its final place on the right.

Keep this guide

By Full Byte Developer

Filed under Dev explainers

Questions about this guide

How do I run bubble sort Python code with custom numbers?

Pass integers after the command, such as python3 bubble_sort.py 5 3 8 1 in ALGO ARCADE, or feed the same list into the function below.

What does the bubble sort algorithm compare?

It compares neighboring values and swaps them when the left value is larger, repeating passes until a pass makes no swaps.

When should I use bubble sort in production?

Almost never for large n. Use it to learn adjacent swaps, or when a tiny nearly-sorted list makes the early-exit variant cheap.

Sources

Next in this stack