How it works
Walk through the array comparing adjacent pairs. If left > right, swap them. Each pass pushes the next largest element to its final position. Repeat until no swaps are needed.
Optimization
// Early termination
if no swaps in a pass:
array is sorted, stop early
// Each pass shrinks unsorted region by 1
if no swaps in a pass:
array is sorted, stop early
// Each pass shrinks unsorted region by 1
Interactive Visualization
Comparing Swapping Sorted
Array
Bar Chart
Step 0 of 0
Pass
0
Comparisons
0
Swaps
0
Sorted
0
Ready. Press Play or Next to start.
ā Sorted
Speed
C++ ā Bubble Sort
void bubbleSort(vector<int>& arr) { int n = arr.size(); for (int i = 0; i < n - 1; i++) { bool swapped = false; for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { swap(arr[j], arr[j + 1]); swapped = true; } } if (!swapped) break; // optimized } }
Complexity
Time (Worst/Avg)
O(N²)
Nested loops over array.
Time (Best)
O(N)
Already sorted, one pass with early exit.
Space
O(1)
In-place, only temp variable.
Stable?
Yes
Equal elements keep relative order.