Sorting Algorithm

Bubble Sort

Repeatedly steps through the array, swapping adjacent elements that are out of order. Each full pass 'bubbles' the largest remaining value to its final position — simple to reason about, but rarely the fastest choice.

BestO(n)
AverageO(n²)
WorstO(n²)
SpaceO(1)
StableYes

Try It — Animated Flow

29
8
44
15
3
37
21
Bubble sort repeatedly walks the array, swapping adjacent out-of-order pairs so the largest value 'bubbles' to the end each pass.
Step 1 / 38
Pointer / current
Comparing
Swapping / removing
Newly inserted
Settled

Java Implementation

Real-Life Usage

Teaching sorting fundamentals
Its simple swap-adjacent-pairs logic makes it the standard first algorithm for learning how sorting and Big-O actually work.
Detecting 'almost sorted' data
With the early-exit optimization, bubble sort finishes in a single O(n) pass when the input is already sorted or nearly so.
Tiny, memory-constrained devices
Its O(1) extra memory and dead-simple logic make it usable on microcontrollers sorting a handful of sensor readings.
Small, bounded playlists
Sorting a short list (a handful of tracks queued by a user) is fast enough that bubble sort's simplicity outweighs its inefficiency at scale.

Trade-offs

Reach for it when
  • The dataset is tiny (a few dozen elements or fewer)
  • The data is already nearly sorted
  • Code simplicity matters more than raw speed
Avoid it when
  • The dataset is large — O(n²) becomes very slow
  • You need a general-purpose production sort (use Arrays.sort / Collections.sort)
  • Performance on random or reversed data matters