Bubble Sort explained step-by-step: adjacent element swaps, early-exit optimization flag, best/worst/average complexity analysis, edge cases, and clean JavaScript code.
Bubble Sort is one of the most intuitive comparison-based sorting algorithms. The algorithm works by repeatedly walking through the array, comparing adjacent elements, and swapping them if they are in the wrong order. With each complete pass, the largest unsorted element "bubbles up" to its final position at the end of the array, just like air bubbles rising to the surface of water.
While Bubble Sort has an O(n²) average and worst-case time complexity, an important optimization (the swapped boolean flag) allows it to terminate in O(n) linear time when given an already sorted array. It serves as an essential teaching tool for understanding loop invariants, in-place swapping, and algorithm stability.
Start at the beginning of the array. Compare each element with its immediate right neighbor (arr[j] and arr[j + 1]).
If arr[j] > arr[j + 1], swap them so the larger value moves one position to the right. Set the swapped flag to true.
After pass i, the last i elements are guaranteed to be in their correct final positions. Only check elements up to index n - i - 1.
If a complete pass finishes without making any swaps (swapped === false), the array is already fully sorted, so exit immediately in O(n) best-case time.
1function bubbleSort(arr) {2 const n = arr.length;3 let swapped;4 5 for (let i = 0; i < n - 1; i++) {6 swapped = false;7 8 // Last i elements are already in place9 for (let j = 0; j < n - i - 1; j++) {10 // Compare adjacent elements11 if (arr[j] > arr[j + 1]) {12 // Swap them if out of order13 [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];14 swapped = true;15 }16 }17 18 // Early termination: array is sorted if no swaps occurred19 if (!swapped) break;20 }21 22 return arr;23}24 25// Example usage:26// bubbleSort([64, 34, 25, 12, 22, 11, 90]); // [11, 12, 22, 25, 34, 64, 90]Play through every comparison, swap, and state change, adjust the speed, or enter custom inputs to test edge cases.
The full interactive roadmap is unlocking — these specialized modules land in upcoming releases.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
Explore the full catalog — 30+ algorithms with more unlocking every release.
Ready — press Play or use step controls to walk through the algorithm.
Comparisons
0
Swaps / Shifts
0
Passes / Depth
0
Elements
10
Test your understanding of Bubble Sort complexity and step mechanics.
Q1.What optimization allows Bubble Sort to achieve O(n) best-case time complexity?
Q2.Why is Bubble Sort considered a stable sorting algorithm?
Apply Bubble Sort to real coding interview questions.
Sort an array with 0s, 1s, and 2s in-place using comparison swaps.