Kazi Rahamatullah
Kazi Rahamatullah
AboutProjectsBlogContact
UsesBooks
ResumeView CV
Kazi Rahamatullah

© Copyright 2026 Kazi Rahamatullah

AboutProjectsBlogBooksUses
Twitter/XGitHubProduct HuntCodeSandbox
Back to Blog
DSASortingBubble SortAlgorithms

Bubble Sort — Algorithm Visualized

Learn bubble sort with step-by-step visuals — adjacent swaps, pass-by-pass animation, O(n²) complexity, code breakdown, and interactive bar chart.

Jul 4, 20264 min read

Introduction

Bubble sort repeatedly compares adjacent elements and swaps them if out of order. After each pass, the largest unsorted value "bubbles" to the end — simple to understand, slow for large inputs at O(n²).

This guide covers:

  1. How bubble sort works — passes and adjacent swaps
  2. Step visualizer — bar chart per pass
  3. Full implementation — nested loops
  4. Complexity — best, average, worst
  5. When to use it — teaching and tiny datasets only

Quick index

#Section
1How it works
2Interactive visualizer
3Full implementation
4Complexity analysis
5Real-life examples

1. How it works

plaintext
Pass 1: compare pairs → largest moves to end
Pass 2: ignore last element, repeat
...
Until no swaps needed
PhaseAction
CompareCheck arr[j] vs arr[j+1]
SwapExchange if left > right
SettleAfter pass i, last i elements sorted

Back to index


2. Interactive visualizer

Bubble Sort — Step Visualizer

Adjacent comparisons and swaps — largest values bubble to the end each pass.

Step 1 / 9 — Unsorted

Unsorted

5
0
3
1
8
2
1
3
9
4
2
5
7
6

n = 7 elements

Step 1 — Input array

for (let i = 0; i < n - 1; i++)
  for (let j = 0; j < n - i - 1; j++)
    if (arr[j] > arr[j+1]) swap

Repeatedly swap adjacent out-of-order pairs.

Time

O(n²)

Space

O(1)

Stable

Yes

Tip

Green bar = element in final position after that pass. Watch how the largest value migrates right each pass.

Back to index


3. Full implementation

js
function bubbleSort(arr) {
  const n = arr.length
  for (let i = 0; i < n - 1; i++) {
    let swapped = false
    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]]
        swapped = true
      }
    }
    if (!swapped) break // already sorted
  }
  return arr
}

Function calls with output

js
// ── Demo calls — output shown on the right ──
const arr = [5, 3, 8, 1, 9, 2, 7]
 
bubbleSort(arr) // → [1, 2, 3, 5, 7, 8, 9]
bubbleSort([3, 1, 2]) // → [1, 2, 3]  (best case, early exit)
bubbleSort([5, 4, 3, 2, 1]) // → [1, 2, 3, 4, 5]  (worst case)
Line blockComplexity
Outer loopn − 1 passes
Inner loopUp to n − i − 1 comparisons
TotalO(n²) worst/average

Back to index


4. Complexity analysis

CaseTimeNotes
BestO(n)Already sorted + early exit
AverageO(n²)Random input
WorstO(n²)Reverse sorted
SpaceO(1)In-place
StableYesEqual elements keep order

Warning

Never use bubble sort in production for n > ~100. Use Array.sort() (Timsort O(n log n)) or a purpose-built algorithm.

Interview Answer

"Is bubble sort stable?"

Yes — we only swap when arr[j] > arr[j+1] (strictly greater), so equal elements never cross.

Back to index


5. Real-life examples

ScenarioWhy bubble sort fits
CS classrooms & whiteboardsEasiest to trace on paper — adjacent swaps are visible
Sorting 5–10 playing cardsn is tiny; simplicity beats O(n log n) overhead
Embedded sensors (n < 20)Arduino reads 12 temperature samples — O(n²) is instant
Detecting if data is already sortedEarly-exit bubble sort returns in O(n) one pass
Introductory coding appsVisualizers (like this one) teach comparison logic

IoT temperature readings

Arduino collects 8 hourly readings — n is tiny so O(n²) bubble sort is instant.

22.1
21.8
23
22.5
21.9
22.3
22
22.7

Index → value

8 hourly readings from sensor — unsorted.

Real-world implementation

function bubbleSort(arr) {
const a = [...arr]
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) breakalready sorted — O(n) exit
}
return a
}

Full working code for the scenario above.

Function calls with output

// ── Function calls with output ──
const readings = [22.1, 21.8, 23.0, 22.5, 21.9, 22.3, 22.0, 22.7]

Side output shows return value after each call — step through to trace execution.

Warning

Real e-commerce, analytics, and database sorting never use bubble sort at scale. It appears in education and micro-datasets only.

Back to index


Summary

Bubble sort teaches comparison-based sorting through adjacent swaps. It is stable and in-place but O(n²) — use it to learn, not to ship.

Next reads: Selection Sort · Insertion Sort · Big O Notation

Share this article

XLinkedInFacebook
Kazi Rahamatullah

Written by

Kazi Rahamatullah

FullStack Developer

X / TwitterGitHubLinkedIn

Subscribe to my newsletter

Stay up to date and get notified when I share new contents.

No spam ever, unsubscribe anytime