0
Comparisons
0
Swaps
0
Sorted
0
Passes
Ready
Status
Unsorted
Comparing
Will swap
Sorted
How It Works
Bubble sort repeatedly steps through the array, comparing adjacent elements and swapping them if they're in the wrong order. The largest unsorted element "bubbles up" to its correct position at the end of each pass.
Algorithm Steps
- Start at the beginning of the array
- Compare adjacent pairs:
arr[j]andarr[j+1] - If
arr[j] > arr[j+1], swap them - After each full pass, the largest unsorted element is in its final position
- Reduce the "active" range by 1 and repeat
Key Code
function* bubbleSortGen(arr) {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
for (let j = 0; j < n - 1 - i; j++) {
yield { type: 'compare', j, j1: j + 1 }; // highlight comparison
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; // swap
yield { type: 'swap', j, j1: j + 1 };
}
}
yield { type: 'sorted', index: n - 1 - i }; // mark sorted
}
}
Using a generator function (function*) lets us pause execution after each step, giving the visualizer control over timing without complex state machines.
Optimization: Early Exit
If a complete pass makes no swaps, the array is already sorted. We can exit early, making best-case performance O(n) instead of O(n²).
Complexity
Best Case
O(n)
Average Case
O(n²)
Worst Case
O(n²)
Space
O(1)
Stable?
Yes