Bubble Sort
Bubble sort is the simplest sorting algorithm, and honestly, it's the one most people learn first. The idea is beautifully simple: repeatedly walk through the list, compare adjacent elements, and swap them if they're in the wrong order. It's called "bubble" sort because the largest elements gradually bubble up to the end of the array.
Trust me, once you see it in action, it clicks immediately. Each pass through the array guarantees that at least one element ends up in its final position. By the time you finish n passes, everything is sorted.
Step-by-Step Visualization
Let's sort [5, 3, 8, 1, 2]. First pass: compare 5 and 3, swap โ [3, 5, 8, 1, 2]. Compare 5 and 8, no swap. Compare 8 and 1, swap โ [3, 5, 1, 8, 2]. Compare 8 and 2, swap โ [3, 5, 1, 2, 8]. Notice how 8 bubbled all the way to the end!
Second pass: compare 3 and 5, no swap. Compare 5 and 1, swap โ [3, 1, 5, 2, 8]. Compare 5 and 2, swap โ [3, 1, 2, 5, 8]. Now 5 is in place. Keep going until no swaps happen in a full pass โ that means you're done.
function bubbleSort(arr) {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
let swapped = false;
for (let j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
swapped = true;
}
}
if (!swapped) break;
}
return arr;
}
console.log(bubbleSort([5, 3, 8, 1, 2]));
Try it Yourself โ
Time Complexity
Bubble sort runs in O(nยฒ) time in both the average and worst cases. That nested loop structure โ outer loop for passes, inner loop for comparisons โ makes it quadratic. Even with the early termination optimization (when no swaps happen), the worst case is still O(nยฒ).
The space complexity is O(1) since you only need a temporary variable for swapping. It sorts in place, which is nice. But let's be real โ O(nยฒ) means bubble sort is impractical for anything beyond tiny datasets.
When to Use Bubble Sort
Here's the honest truth: almost never in production. But it's perfect for learning because the logic is so clear. It's also useful when the data is nearly sorted โ with the swapped flag optimization, it can finish in O(n) time on already-sorted input.
Use bubble sort in interviews to demonstrate you understand the basics, or when you need a dead-simple implementation and performance doesn't matter. For everything else, reach for merge sort or quick sort.
Try it Yourself โ