Skip to main content
← All posts

Bubble Sort: Mechanism, Complexity Analysis & Interactive Visualizer

Super AdminNov 5, 20269 min readArticle
Bubble Sort: Mechanism, Complexity Analysis & Interactive Visualizer
Basic Sorting · Article 1 of 62

Bubble Sort

The classic teaching algorithm: repeatedly walk the array, swap any out-of-order neighbors, and let the largest element bubble to the top of each pass.

How it works

Bubble Sort makes repeated left-to-right passes over the array. On each pass it compares every adjacent pair of elements and swaps them if they are in the wrong order. Each full pass guarantees that one more of the largest unsorted values has reached its final position at the end of the array, like a bubble of air rising to the surface of water.

  1. Start at index 0.
  2. Compare arr[i] with arr[i+1].
  3. If they are out of order, swap them.
  4. Move one step right and repeat until you reach the end of the unsorted portion.
  5. After each pass, the last position of the unsorted portion is fixed; shrink the working range and repeat until no swaps are possible.

Complexity

Best time
O(n²)
Average time
O(n²)
Worst time
O(n²)
Extra space
O(1)
Stable
Yes
In-place
Yes
Plain Bubble Sort always does n − 1 passes, even if the array is already sorted. The next article — Optimized Bubble Sort — fixes this with an early-exit flag.

Interactive visualization

Pseudocode

procedure bubbleSort(A):
  n ← length(A)
  for i from 0 to n − 2:
    for j from 0 to n − i − 2:
      if A[j] > A[j+1]:
        swap A[j], A[j+1]

JavaScript implementation

function bubbleSort(arr) {
  const n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    for (let j = 0; j < n - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
      }
    }
  }
  return arr;
}

Pros and cons

Pros

  • Trivially simple to understand and implement.
  • Stable: equal keys keep their original order.
  • In-place: needs only O(1) extra memory.
  • Detects "already sorted" trivially when paired with an early-exit flag.

Cons

  • Quadratic in best, average, and worst case — useless beyond a few hundred elements.
  • Performs many redundant swaps compared to selection sort.
  • Cache-friendly but still slower than insertion sort in practice.
  • Almost never used in production. Mainly a teaching tool.

When (not) to use it

  • Teach the idea of comparison-based sorting. It is the canonical first algorithm.
  • Tiny arrays (n < 10). Performance differences disappear, and the simplicity is a feature.
  • Never use it for real workloads. Insertion sort dominates it on small inputs, and any O(n log n) sort dominates it on large ones.
Up next: Optimized Bubble Sort — same idea, but with an early-exit flag that detects an already-sorted array in a single linear pass.
Share:
Share on X
Share on LinkedIn
Share on Facebook
Share on Reddit
Share on WhatsApp
Share on Telegram
Copy link

Related reading