Bubble Sort is one of the simplest sorting algorithms to understand.
It repeatedly compares adjacent elements and swaps them if they’re in the wrong order — just like bubbles rising to the top of water, the largest elements “bubble up” to the end of the array.
In this post, we’ll walk through:
- How Bubble Sort works
- A JavaScript implementation
- A step-by-step dry run
- An optimized version (early exit)
- Time & space complexity
- ES6 destructuring swap explanation
What is Bubble Sort?
Bubble Sort works by repeatedly traversing the array and swapping adjacent elements if they are out of order.
After each full pass, the largest element among the unsorted section ends up at its correct final position.
This continues until the array is sorted.
JavaScript Implementation (Ascending Order)
const bubble = (arr) => {
let n = arr.length;
for (let i = n - 1; i >= 0; i--) {
for (let j = 0; j < i; j++) {
if (arr[j] > arr[j + 1]) {
// ES6 destructuring swap
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
};
console.log(bubble([12, 45, 2, 1, 54, 3]));
// => [1, 2, 3, 12, 45, 54]
Step-by-Step Dry Run
Given the array:
[12, 45, 2, 1, 54, 3]
Pass 1
Compare and swap adjacent pairs:
12 45 → OK
45 2 → swap
45 1 → swap
45 54 → OK
54 3 → swap
After Pass 1:
[12, 2, 1, 45, 3, 54]
Pass 2
12 2 → swap
12 1 → swap
12 45 → OK
45 3 → swap
After Pass 2:
[2, 1, 12, 3, 45, 54]
This continues until the array becomes:
[1, 2, 3, 12, 45, 54]
Optimized Bubble Sort (Early Exit)
One major inefficiency of basic Bubble Sort is that it continues looping even when the array is already sorted.
We can fix that using a swapped flag:
const bubbleOptimized = (arr) => {
let n = arr.length;
for (let i = n - 1; i >= 0; i--) {
let swapped = false;
for (let j = 0; j < i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
swapped = true;
}
}
if (!swapped) break; // No swaps = already sorted
}
return arr;
};
With this optimization:
- Best-case time becomes O(n)
- Average and worst cases remain O(n²)
Time & Space Complexity (Summary)
| Scenario | Complexity |
|---|---|
| Best Case (already sorted) | O(n) with optimization, O(n²) without |
| Average Case | O(n²) |
| Worst Case | O(n²) |
| Space Complexity | O(1) — in-place |
| Stable? | Yes — Bubble Sort is stable by default |
Understanding the ES6 Swap
Throughout this post, we used:
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
This works because:
The right-hand side is evaluated first, producing something like [1, 12]
Then JavaScript assigns values left-to-right:
arr[j] = 1arr[j + 1] = 12
It’s the same as writing:
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
But cleaner.
Final Thoughts
Bubble Sort is not the most efficient algorithm, but it is:
- Easy to understand
- Great for learning swapping & comparisons
- Stable
- Good for demonstrating algorithmic thinking
If you're practicing for interviews or learning sorting fundamentals, mastering Bubble Sort is a solid first step.
Top comments (0)