Python Algorithms

Bubble Sort in Python

Bubble sort repeatedly compares neighboring values and swaps them when they are out of order.

What is Bubble Sort?

Bubble sort repeatedly compares neighboring values and swaps them when they are out of order.

Sort a Python list with bubble sort and an early-exit optimization.

When should you use it?

  • Practice problem solving and data structures.
  • Process data when every algorithm step must be explicit.
  • Prepare for programming exercises, exams, and interviews.

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]))

Expected output

[1, 2, 4, 5, 8]

How it works

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 Python IDE →