Visualizer › Sorting
Bubble Sort
Repeatedly compares neighbouring elements and swaps them when they are in the wrong order, so the largest element "bubbles" to the end after each pass.
How it works
- After pass k, the last k elements are in their final place.
- Stop early when a pass makes no swaps — that makes the best case O(n).
- Simple to write, but too slow for large inputs.
Complexity
- Best time: O(n)
- Average time: O(n²)
- Worst time: O(n²)
- Extra space: O(1)
- Stable: yes
Code (Python)
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 aPractise: Arrays problems