Bubble Sort Algorithm
Bubble Sort repeatedly steps through the array, compares adjacent elements, and swaps them if they are in the wrong order. Larger elements 'bubble' to the end of the array with each pass.
Algorithm Steps
- Compare each pair of adjacent elements from the start of the array.
- Swap them if the left element is greater than the right one.
- Repeat for the entire array; after each pass, the largest unsorted element settles at the end.
- Stop early if a pass completes with no swaps (array is already sorted).
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
return arr
print(bubble_sort([5, 1, 4, 2, 8]))
Complexity
| Case | Time | Space |
|---|---|---|
| Best (already sorted, with flag) | O(n) | O(1) |
| Average | O(n²) | O(1) |
| Worst | O(n²) | O(1) |
Key Characteristics
- Stable sort — equal elements retain their relative order.
- Simple to implement, but inefficient for large datasets compared to Merge Sort or Quick Sort.
- Mainly used for teaching sorting concepts and for very small or nearly-sorted datasets.
Pass-by-Pass Trace of [5, 1, 4, 2, 8]
Following the sample input through each pass shows the early-exit flag earning its keep.
| Pass | Comparisons | Swaps | Array after the pass |
|---|---|---|---|
| 1 | 4 | 3 (5↔1, 5↔4, 5↔2) | [1, 4, 2, 5, 8] |
| 2 | 3 | 1 (4↔2) | [1, 2, 4, 5, 8] |
| 3 | 2 | 0 | [1, 2, 4, 5, 8], loop stops |
The array was sorted after pass 2, but the algorithm only knows that once a pass finishes with no swaps, so pass 3 confirms it. Without the flag, a fourth pass would run for nothing. In total, nine comparisons were made instead of the ten a plain version would perform.
Counting the Work
In the worst case, the first pass compares n − 1 pairs, the next n − 2, and so on down to 1. The total is n(n − 1)/2 comparisons, which is where the quadratic time comes from. A reversed array also needs one swap for every comparison, so a list of 1,000 reversed items needs roughly half a million swaps. That is the clearest reason the algorithm is avoided for large data.
Shrinking the range with the last swap
A smarter variant remembers where the last swap happened. Everything after that point is already in its final place, so the next pass can stop there instead of reducing the range by just one.
def bubble_sort_last_swap(arr):
n = len(arr)
while n > 1:
last_swap = 0
for j in range(1, n):
if arr[j - 1] > arr[j]:
arr[j - 1], arr[j] = arr[j], arr[j - 1]
last_swap = j
n = last_swap # 0 means no swaps, loop ends
return arr
print(bubble_sort_last_swap([3, 2, 1, 4, 5, 6, 7]))
For the input above, the first pass ends with its last swap near the front, so the second pass covers only two elements instead of six.
Cocktail shaker sort
Another variant alternates direction: left to right, then right to left. It fixes the "turtle" problem, where a small value near the end moves only one step left per pass in normal bubble sort.
Bubble, Selection and Insertion Sort Compared
| Property | Bubble | Selection | Insertion |
|---|---|---|---|
| Best case | O(n) with flag | O(n²) | O(n) |
| Worst case | O(n²) | O(n²) | O(n²) |
| Stable | Yes | No in the usual array version | Yes |
| Swaps | Many | At most n − 1 | Shifts instead of swaps |
In practice insertion sort usually beats bubble sort on the same data, and selection sort is preferred only when writes are very costly.
Errors Beginners Make
- Looping the inner index to
n - iinstead ofn - 1 - i, which reads past the end witharr[j + 1]. - Resetting the
swappedflag outside the outer loop, so the early exit never triggers. - Using
>=in the comparison, which swaps equal items and makes the sort unstable. - Forgetting that the list is sorted in place, then being surprised that the original order is gone.
Takeaway: learn bubble sort for the idea of adjacent swaps and stability, then use your language's built-in sort for real work.