JavaScript Program for Bubble Sort Algorithm
for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { let temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } }.Examples
How to Think About It
Algorithm
Code
function bubbleSort(arr) { for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { let temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; } console.log(bubbleSort([3, 1, 4, 2]));
Dry Run
Let's trace sorting [3, 1, 4, 2] through the bubble sort code.
Start first pass
Array: [3, 1, 4, 2]
Compare 3 and 1
3 > 1, swap -> [1, 3, 4, 2]
Compare 3 and 4
3 < 4, no swap -> [1, 3, 4, 2]
Compare 4 and 2
4 > 2, swap -> [1, 3, 2, 4]
End first pass
Largest element 4 is at the end
Start second pass
Array: [1, 3, 2, 4]
Compare 1 and 3
1 < 3, no swap -> [1, 3, 2, 4]
Compare 3 and 2
3 > 2, swap -> [1, 2, 3, 4]
End second pass
Second largest element 3 is in place
Start third pass
Array: [1, 2, 3, 4]
Compare 1 and 2
1 < 2, no swap -> [1, 2, 3, 4]
End third pass
No swaps needed, array sorted
| Pass | Array State After Pass |
|---|---|
| 1 | [1, 3, 2, 4] |
| 2 | [1, 2, 3, 4] |
| 3 | [1, 2, 3, 4] |
Why This Works
Step 1: Compare adjacent elements
The code checks pairs next to each other using if (arr[j] > arr[j + 1]) to find if they are out of order.
Step 2: Swap if needed
If the left element is bigger, it swaps places with the right one to move bigger values toward the end.
Step 3: Repeat passes
Multiple passes ensure all elements bubble up to their correct position, with the largest settling at the end each time.
Alternative Approaches
function bubbleSortOptimized(arr) { let swapped; for (let i = 0; i < arr.length; i++) { swapped = false; for (let j = 0; j < arr.length - i - 1; 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(bubbleSortOptimized([3, 1, 4, 2]));
function sortWithBuiltIn(arr) { return arr.sort((a, b) => a - b); } console.log(sortWithBuiltIn([3, 1, 4, 2]));
Complexity: O(n²) time, O(1) space
Time Complexity
Bubble sort uses two nested loops over the array, making it O(n²) in the worst and average cases.
Space Complexity
It sorts the array in place, so it uses O(1) extra space.
Which Approach is Fastest?
The optimized bubble sort can be faster on nearly sorted data, but built-in sort methods are generally much faster for large arrays.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Basic Bubble Sort | O(n²) | O(1) | Learning sorting basics |
| Optimized Bubble Sort | O(n) best, O(n²) worst | O(1) | Nearly sorted arrays |
| Built-in sort() | O(n log n) | O(log n) | General use, large arrays |