Bubble Sort
Reading time: 10 minutes
Bubble sort is one of the simplest sorting algorithms. It works by repeatedly stepping through the array, comparing adjacent elements, and swapping them if they are in the wrong order. The algorithm gets its name because smaller elements "bubble" to the top (beginning) of the array while larger elements sink to the bottom (end).
Interactive Visualization
Watch bubble sort in action. Click Start to begin, adjust the speed, or change the array size.
How It Works
Bubble sort makes multiple passes through the array:
Compare adjacent elements (positions
iandi+1)Swap them if the left element is greater than the right element
Repeat until reaching the end of the unsorted portion
After each pass, the largest unsorted element is in its final position
Continue passes until no swaps are needed
Implementation
Complexity Analysis
Case | Time Complexity | When It Occurs |
|---|---|---|
Best | O(n) | Array is already sorted (with early termination optimization) |
Average | O(n²) | Random order |
Worst | O(n²) | Array is sorted in reverse order |
Space complexity: O(1) — bubble sort is an in-place algorithm.
When to Use Bubble Sort
Bubble sort is rarely used in practice due to its O(n²) complexity. However, it has some niche uses:
Educational purposes — its simplicity makes it ideal for teaching sorting concepts
Nearly sorted data — with the early termination optimization, it performs well when the array is almost sorted
Small datasets — for very small arrays (< 10 elements), the overhead of more complex algorithms may not be worth it
For production code, prefer algorithms like quick sort, merge sort, or the built-in sorting functions in your language.
Summary
Bubble sort compares and swaps adjacent elements repeatedly
It has O(n²) time complexity in the average and worst cases
The early termination optimization improves best-case performance to O(n)
It is an in-place, stable sorting algorithm
Use it for learning; prefer faster algorithms for real applications