Bubble Sort
A simple algorithm that sorts by comparing neighbouring elements.
#How does it work?
Bubble sort walks through the array again and again, comparing elements that sit next to each other. If the left one is larger than the right one, it swaps them.
At the end of every pass, the largest element of the unsorted part rises to the end of the array like a bubble in water and settles into its final place. That is where the name comes from.
If a whole pass makes no swaps, the array is sorted and the algorithm can stop early.
#Live animation
Press Play or step through. Each step compares two neighbouring elements.
for i = 0 to n - 2swapped = falsefor j = 0 to n - i - 2if a[j] > a[j + 1]swap(a[j], a[j + 1]); swapped = trueif not swapped: break
#Step by step
- 01Start at the beginning of the array and compare the first two elements.
- 02If the left element is larger than the right one, swap them.
- 03Move one position to the right and compare the next pair; continue until the end.
- 04When the pass ends, the largest element is at the far right. Ignore it in the next pass.
- 05Repeat until a pass makes no swaps or there is nothing left to sort.
#Example code
The same algorithm in 8 languages. Every program is compiled, run and checked to print the same output.
def bubble_sort(a: list[int]) -> None:
n = len(a)
for i in range(n - 1):
swapped = False
# After pass i, the last i elements are already in place.
for j in range(n - i - 1):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped: # no swaps: already sorted
break
numbers = [5, 1, 4, 2, 8, 3]
bubble_sort(numbers)
print(*numbers)#Complexity
| Best | O(n) |
|---|---|
| Average | O(n²) |
| Worst | O(n²) |
| Extra memory | O(1) |
| Stable? | Yes |
| In place? | Yes |
The O(n) best case applies when the array is already sorted and the early exit (swapped flag) is used: a single pass makes n-1 comparisons. A reversed array needs about n²/2 comparisons and as many swaps.
#When to use it?
Bubble sort is great for learning: it shows comparisons, swaps and loop invariants very clearly. In real projects it is slow on large data; merge sort, quick sort or your language's built-in sort are better choices. It can still be reasonable for very small or nearly sorted arrays.
#Practice
Log in to answer questions and save your progress.
Easy
What does bubble sort do on each pass?
- 1Compares neighbours and swaps them if needed
- 2Splits the array in half
- 3Picks the middle element as pivot
- 4Puts the elements into a hash table
What is the worst-case time complexity of bubble sort?
- 1O(n)
- 2O(n log n)
- 3O(n²)
- 4O(log n)
Is bubble sort a stable algorithm?
- 1Yes
- 2No
Medium
What does [5, 1, 4, 2] look like after the first pass?
- 1[1, 4, 2, 5]
- 2[1, 2, 4, 5]
- 3[1, 5, 4, 2]
- 4[4, 1, 2, 5]
Hard
With an early exit when a pass makes no swaps, what is the best-case complexity on an already sorted array?
- 1O(n)
- 2O(n²)
- 3O(n log n)
- 4O(1)