0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program for Bubble Sort Algorithm

A JavaScript program for bubble sort repeatedly swaps adjacent elements if they are in the wrong order using nested loops, like 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

Input[3, 1, 4, 2]
Output[1, 2, 3, 4]
Input[5, 4, 3, 2, 1]
Output[1, 2, 3, 4, 5]
Input[]
Output[]
🧠

How to Think About It

To sort an array with bubble sort, think of repeatedly passing through the list and comparing each pair of neighbors. If a pair is out of order, swap them. Keep doing this until no swaps are needed, meaning the list is sorted.
📐

Algorithm

1
Get the input array.
2
Repeat for each element in the array:
3
Compare each pair of adjacent elements.
4
If the left element is greater than the right, swap them.
5
After each full pass, the largest unsorted element moves to its correct position.
6
Stop when no swaps happen in a full pass.
💻

Code

javascript
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]));
Output
[1, 2, 3, 4]
🔍

Dry Run

Let's trace sorting [3, 1, 4, 2] through the bubble sort code.

1

Start first pass

Array: [3, 1, 4, 2]

2

Compare 3 and 1

3 > 1, swap -> [1, 3, 4, 2]

3

Compare 3 and 4

3 < 4, no swap -> [1, 3, 4, 2]

4

Compare 4 and 2

4 > 2, swap -> [1, 3, 2, 4]

5

End first pass

Largest element 4 is at the end

6

Start second pass

Array: [1, 3, 2, 4]

7

Compare 1 and 3

1 < 3, no swap -> [1, 3, 2, 4]

8

Compare 3 and 2

3 > 2, swap -> [1, 2, 3, 4]

9

End second pass

Second largest element 3 is in place

10

Start third pass

Array: [1, 2, 3, 4]

11

Compare 1 and 2

1 < 2, no swap -> [1, 2, 3, 4]

12

End third pass

No swaps needed, array sorted

PassArray 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

Optimized Bubble Sort with Early Stop
javascript
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]));
Stops early if no swaps happen, improving speed on nearly sorted arrays.
Using JavaScript's built-in sort
javascript
function sortWithBuiltIn(arr) {
  return arr.sort((a, b) => a - b);
}

console.log(sortWithBuiltIn([3, 1, 4, 2]));
Much faster and simpler but does not show bubble sort logic.

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.

ApproachTimeSpaceBest For
Basic Bubble SortO(n²)O(1)Learning sorting basics
Optimized Bubble SortO(n) best, O(n²) worstO(1)Nearly sorted arrays
Built-in sort()O(n log n)O(log n)General use, large arrays
💡
Use an early stop flag to end bubble sort early if the array is already sorted.
⚠️
Forgetting to reduce the inner loop length each pass causes unnecessary comparisons.