Skip to content
Devtoolry

Lists and algorithms · intermediate

Python Program for Bubble Sort

Sort a list with bubble sort in Python, step through every swap in the visualizer, stop early when the list is already sorted, and compare with sorted().

Bubble sort repeatedly walks through the list and swaps neighbours that are in the wrong order. After each pass the largest remaining value has "bubbled up" to the end. It is slow for big lists (it compares about n²/2 pairs), but it is the easiest sorting algorithm to follow step by step, which makes it ideal for learning.

The program

Python
def bubble_sort(items):
    items = items.copy()
    n = len(items)
    for end in range(n - 1, 0, -1):
        swapped = False
        for i in range(end):
            if items[i] > items[i + 1]:
                items[i], items[i + 1] = items[i + 1], items[i]
                swapped = True
        if not swapped:
            break
    return items

data = [5, 1, 4, 2, 8]
print(bubble_sort(data))
print(data)
Output
[1, 2, 4, 5, 8]
[5, 1, 4, 2, 8]

How it works

  1. items.copy() sorts a copy, so the caller's list stays unchanged (the last line proves it).
  2. end marks where the unsorted part stops. After each pass it moves one place left, because the last element is already in place.
  3. The inner loop compares neighbours and swaps them with tuple unpacking when the left one is bigger.
  4. swapped records whether anything moved. A pass with no swaps means the list is sorted, so break stops early; an already sorted list needs only one pass.

Watch it run line by line

This is the best program to visualize: watch items inside bubble_sort change after every swap, i walk along the list, and end shrink after each pass. Count the steps for [1, 2, 3, 4, 5] to see the early exit.

“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.

Another way: What to use in real code

Python's built-in sort (Timsort) is much faster. list.sort() sorts in place and returns None; sorted() returns a new list. Both accept key= and reverse=.

Python
data = [5, 1, 4, 2, 8]
print(sorted(data, reverse=True))
data.sort()
print(data)
print(sorted(["pear", "Fig", "apple"], key=str.lower))
Output
[8, 5, 4, 2, 1]
[1, 2, 4, 5, 8]
['apple', 'Fig', 'pear']

Common mistakes

  • Looping i over range(n) instead of range(end): items[i + 1] then goes past the end and raises IndexError.
  • Writing data = data.sort(): sort() returns None, so data becomes None.
  • Swapping with two separate assignments (items[i] = items[i + 1]; items[i + 1] = items[i]), which copies one value over the other.

Try it yourself

  • Count the number of swaps and comparisons for a sorted, a reversed and a random list.
  • Change the comparison so the list is sorted in descending order.
  • Sort a list of (name, age) tuples by age.

Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 Python examples, or write your own program in the online Python Compiler.