Editor

Python Program for Bubble Sort

Intermediate · Searching and sorting

Bubble sort is a simple sorting algorithm that repeatedly compares neighbouring items and swaps them when they are in the wrong order. After each pass through the list, the largest remaining number has bubbled up to the end. This program prints the list after every pass and stops early once a pass makes no swaps.

Program

bubble_sort.py
numbers = [5, 1, 4, 2, 8, 3]
print("Original list:", numbers)
n = len(numbers)
for i in range(n - 1):
swapped = False
# The last i numbers are already in place, so skip them
for j in range(n - 1 - i):
if numbers[j] > numbers[j + 1]:
numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
swapped = True
print(f"After pass {i + 1}:", numbers)
if not swapped:
print("No swaps in this pass, so the list is sorted")
break
print("Sorted list:", numbers)
Output
Original list: [5, 1, 4, 2, 8, 3]
After pass 1: [1, 4, 2, 5, 3, 8]
After pass 2: [1, 2, 4, 3, 5, 8]
After pass 3: [1, 2, 3, 4, 5, 8]
After pass 4: [1, 2, 3, 4, 5, 8]
No swaps in this pass, so the list is sorted
Sorted list: [1, 2, 3, 4, 5, 8]

How it works

  1. The outer loop runs one pass at a time, and n - 1 passes are always enough.
  2. The inner loop compares each pair numbers[j] and numbers[j + 1] and swaps them if the left one is bigger.
  3. Each pass fixes one more number at the end, so the inner loop stops i places earlier every time.
  4. swapped records whether anything moved: a pass with no swaps means the list is sorted, so break ends the sort early.
  5. Bubble sort makes about n x n comparisons, so it is used for teaching rather than for large lists.

Another way to write it

Using the built-in sort

Using the built-in sort
numbers = [5, 1, 4, 2, 8, 3]
print("Ascending:", sorted(numbers))
print("Descending:", sorted(numbers, reverse=True))
Output
Ascending: [1, 2, 3, 4, 5, 8]
Descending: [8, 5, 4, 3, 2, 1]

In real programs, use sorted() or list.sort(). Python's built-in sort is much faster than bubble sort on large lists.

Try it yourself

Change the comparison so the list is sorted from largest to smallest.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises