Algorithm Deep Dives

Bubble Sort Explained

Updated June 8, 2026 6 min read

Bubble Sort is the first sorting algorithm almost everyone learns. It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order — letting larger values 'bubble' to the top. It is rarely used in production, but it is unbeatable as a teaching tool.

How Bubble Sort works

On each pass, Bubble Sort walks from the start of the array to the end, comparing each pair of neighbours. If the left element is bigger than the right, they swap. After the first pass the largest element is guaranteed to be at the end. After the second pass the two largest are in place, and so on, until the whole array is sorted.

Pseudocode

for i from 0 to n-1:
  swapped = false
  for j from 0 to n-2-i:
    if a[j] > a[j+1]:
      swap(a[j], a[j+1])
      swapped = true
  if not swapped:
    break  // already sorted

The swapped flag is the key optimization: if a full pass makes no swaps, the array is sorted and we stop early.

Complexity and the swapped-flag trick

Bubble Sort is O(n²) on average and worst case because of its nested loops. But with the early-exit flag it reaches O(n) on already-sorted data, making it adaptive. Space is O(1) and it is stable. Watch it run in the visualizer to see the largest values rise to the end pass by pass.

Should you ever use it?

In production, almost never — Insertion Sort beats it for small arrays and built-in sorts beat both. But Bubble Sort's value is pedagogical: it makes comparison and swapping crystal clear, which is why it remains the 'Hello World' of sorting. See how it compares in our Bubble vs Insertion Sort guide.

Frequently asked questions

What is the time complexity of Bubble Sort? +
Bubble Sort is O(n²) in the average and worst case. With the swapped-flag optimization it reaches O(n) on already-sorted data. Space complexity is O(1) and it is stable.
Why is Bubble Sort still taught? +
Because it is the simplest algorithm to understand and implement, clearly demonstrating comparison, swapping, and early termination. It motivates students to learn more efficient O(n log n) algorithms.
Is Bubble Sort ever used in real life? +
Rarely. It can be useful on tiny or nearly-sorted datasets, or in extremely memory-constrained embedded systems where code simplicity matters more than speed.

See it in motion

Watch this algorithm and 9 others run step by step in our free interactive visualizer.

▶ Launch Visualiser

Related articles

← Back to all articles