Bubble Sort Explained
The simplest sorting algorithm that repeatedly steps through the list
How Bubble Sort Works
Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.
The pass through the list is repeated until the list is sorted. The algorithm gets its name because smaller elements "bubble" to the top of the list.
Key Characteristics:
- Time Complexity: O(n²) in worst and average cases
- Space Complexity: O(1) - it's an in-place sorting algorithm
- Stable: Maintains relative order of equal elements
- Not efficient for large datasets
Interactive Demonstration
Algorithm Steps:
- Start at the beginning of the array
- Compare the current element with the next element
- If they are in wrong order, swap them
- Move to the next pair
- Repeat until no more swaps are needed
Implementation Details
function bubbleSort(arr) {
let n = arr.length;
let swapped;
do {
swapped = false;
for (let i = 0; i < n - 1; i++) {
// Compare adjacent elements
if (arr[i] > arr[i + 1]) {
// Swap if they are in wrong order
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
swapped = true;
}
}
// After each pass, largest element bubbles to end
n--;
} while (swapped);
return arr;
}
Optimization Tip
You can optimize by reducing the inner loop size after each pass since the largest elements bubble to the end.
When to Use
Only suitable for small datasets or nearly sorted data. For larger datasets, consider more efficient algorithms like quicksort or mergesort.