Bubble Sort
See it animated in Zerethon Tools ↗Repeatedly swap adjacent out-of-order pairs; stop early when a pass makes no swap — O(n²).
Implementations
Sign in to open in IDE
Sign in with your Zerethon account to create your own copy of this sample.
Files
# Bubble Sort
Zerethon Official Sample `bubble-sort`, version 1.2.0, Python 3.12.
- `bubble_sort.py` — the algorithm, as shown in Zerethon Tools
- `main.py` — entry file: a short demonstration
- `test_bubble_sort.py` — checks; set it as the entry file to run them
This project is your own copy. Changing it never changes the official sample.
See the algorithm animated: https://tools.zerethon.com/bubble-sort-visualizer
"""Bubble Sort (Zerethon Official Sample: bubble-sort 1.2.0)."""
def bubble_sort(a):
n = len(a)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped: # already sorted
break
return a
from bubble_sort import bubble_sort
numbers = [38, 27, 43, 3, 9, 82, 10, 27]
print("Before:", numbers)
result = bubble_sort(list(numbers))
print("After: ", result)
print("Same as sorted():", result == sorted(numbers))
# Checks for bubble_sort. To run them, set this file as the entry file
# (the ▶ button next to it in Files) and press Run.
from bubble_sort import bubble_sort
def numbers(seed, count):
"""Deterministic pseudo-random integers in [-50, 49]."""
out = []
for _ in range(count):
seed = (seed * 1103515245 + 12345) % 2**31
out.append(seed % 100 - 50)
return out
cases = [[], [1], [2, 1], [1, 2, 3], [3, 2, 1], [5, 1, 5, 1, 5], [-3, 0, -1, 2]]
cases += [numbers(seed, size) for seed, size in ((1, 10), (2, 50), (3, 200))]
for case in cases:
got = bubble_sort(list(case))
assert got == sorted(case), f"bubble_sort({case[:6]}...) = {got[:6]}..."
print(f"All {len(cases)} checks passed.")
Source: Zerethon Official Sample. Algorithm as shown in the Zerethon Tools Bubble Sort Visualizer.