← Back to Index

🫧 Bubble Sort

Sorting · O(n²)
0
Comparisons
0
Swaps
0
Sorted
0
Passes
Ready
Status
Unsorted
Comparing
Will swap
Sorted

How It Works

Bubble sort repeatedly steps through the array, comparing adjacent elements and swapping them if they're in the wrong order. The largest unsorted element "bubbles up" to its correct position at the end of each pass.

Algorithm Steps

  1. Start at the beginning of the array
  2. Compare adjacent pairs: arr[j] and arr[j+1]
  3. If arr[j] > arr[j+1], swap them
  4. After each full pass, the largest unsorted element is in its final position
  5. Reduce the "active" range by 1 and repeat

Key Code

function* bubbleSortGen(arr) {
  const n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    for (let j = 0; j < n - 1 - i; j++) {
      yield { type: 'compare', j, j1: j + 1 };        // highlight comparison
      if (arr[j] > arr[j + 1]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];  // swap
        yield { type: 'swap', j, j1: j + 1 };
      }
    }
    yield { type: 'sorted', index: n - 1 - i };        // mark sorted
  }
}

Using a generator function (function*) lets us pause execution after each step, giving the visualizer control over timing without complex state machines.

Optimization: Early Exit

If a complete pass makes no swaps, the array is already sorted. We can exit early, making best-case performance O(n) instead of O(n²).

Complexity

Best Case
O(n)
Average Case
O(n²)
Worst Case
O(n²)
Space
O(1)
Stable?
Yes