Bubble Sort Algorithm Explained

Bubble sort repeatedly steps through a list, comparing adjacent elements and swapping them if they're in the wrong order, until no swaps are needed.

Published November 14, 2026

Bubble sort repeatedly steps through a list, swapping adjacent items that are in the wrong order, so the largest values 'bubble' to the end. It is simple but slow: O(n²).

The concept

After pass 1 the largest item is in place, after pass 2 the second largest, and so on. If a pass makes no swaps the list is sorted and you can stop early.

It is useful for teaching and tiny or nearly sorted lists, but practical code uses faster algorithms.

Pass 1 on [5, 3, 8, 1]

  1. Compare 5,3 → swap: [3, 5, 8, 1]
  2. Compare 5,8 → keep
  3. Compare 8,1 → swap: [3, 5, 1, 8]
  4. 8 is now in its final place

Practical examples

JavaScript

function bubble(a) {
  a = [...a]
  for (let i = 0; i < a.length; i++) {
    let swapped = false
    for (let j = 0; j < a.length - 1 - i; j++)
      if (a[j] > a[j + 1]) { [a[j], a[j + 1]] = [a[j + 1], a[j]]; swapped = true }
    if (!swapped) break
  }
  return a
}

Python

def bubble(a):
    for i in range(len(a)):
        for j in range(len(a) - 1 - i):
            if a[j] > a[j+1]: a[j], a[j+1] = a[j+1], a[j]
    return a

Complexity

best O(n) with early exit · average/worst O(n²) · space O(1) · stable

Common mistakes

  • No early-exit optimisation.
  • Looping the inner pass over already sorted tail.
  • Using it for large data.

Key takeaways

  • Swap neighbours repeatedly.
  • O(n²) time, O(1) space, stable.
  • Educational, not practical.

FAQ

Is bubble sort stable?

Yes, equal items keep their order.

What should I use instead?

Built-in sort (Timsort/introsort) in real code.

More General articles