Back to DSA Guide Catalog

Algorithmmedium

Bubble Sort Complete Guide

Bubble sort repeatedly compares adjacent elements and swaps out-of-order pairs until the list is sorted.

It is mainly valuable as a teaching algorithm because its mechanics are intuitive and visual.

At scale, bubble sort is usually replaced by faster O(n log n) algorithms.

Typical Complexity Baseline

MetricValue
Complexity Note 1Average/Worst O(n^2)
BestO(n) with early-exit optimization

Video Explainer

Prefer video learning? This explainer gives a quick visual walkthrough of the core idea before you dive into the detailed sections below.

Sorting Visualizer

Step through Bubble Sort to see how the list changes over time.

Bubble Sort
Bubble SortStep 1 / 59

Start with unsorted values.

9
3
7
1
8
2
6
4
5

Core Concepts

Learn the core building blocks and terminology in one place before comparisons, so the mechanics are clear and duplicates are removed.

Outer pass

What it is: Each pass bubbles the largest remaining element to the end.

Why it matters: Outer pass is a required building block for understanding how Bubble Sort stays correct and performant on large inputs.

Adjacent comparison

What it is: Compare index i and i+1, then swap if needed.

Why it matters: Adjacent comparison is a required building block for understanding how Bubble Sort stays correct and performant on large inputs.

Swap operation

What it is: In-place exchange of adjacent values.

Why it matters: Swap operation is a required building block for understanding how Bubble Sort stays correct and performant on large inputs.

Early-exit flag

What it is: Stop when a full pass makes zero swaps.

Why it matters: Early-exit flag is a required building block for understanding how Bubble Sort stays correct and performant on large inputs.

Shrinking boundary

What it is: Ignore already sorted tail section in later passes.

Why it matters: Shrinking boundary is a required building block for understanding how Bubble Sort stays correct and performant on large inputs.

Adjacent swap

What it is: Swap two neighboring values only.

Why it matters: Swap two neighboring values only. In Bubble Sort, this definition helps you reason about correctness and complexity when inputs scale.

Stable sort

What it is: Equal values preserve relative order.

Why it matters: Equal values preserve relative order. In Bubble Sort, this definition helps you reason about correctness and complexity when inputs scale.

Best case

What it is: With early-exit, sorted input can finish in O(n).

Why it matters: With early-exit, sorted input can finish in O(n). In Bubble Sort, this definition helps you reason about correctness and complexity when inputs scale.

Worst case

What it is: Reverse-sorted input needs O(n^2) comparisons/swaps.

Why it matters: Reverse-sorted input needs O(n^2) comparisons/swaps. In Bubble Sort, this definition helps you reason about correctness and complexity when inputs scale.

In-place

What it is: Uses constant extra memory beyond input array.

Why it matters: Uses constant extra memory beyond input array. In Bubble Sort, this definition helps you reason about correctness and complexity when inputs scale.

Putting It All Together

Follow one Bubble Sort run end-to-end: compare neighbors, swap when needed, and stop early when no swaps occur.

Step 1

Outer pass

Each pass bubbles the largest remaining element to the end.

Pass 1: largest value moves to the endBefore pass51428bubbleAfter pass14258sorted suffix starts here

Why this step matters: The sorted suffix grows one element per pass, reducing work in subsequent passes.

Step 2

Adjacent comparison

Compare index i and i+1, then swap if needed.

Compare adjacent pair at i=1 and i+1=2Current state10412253844 > 2 ? yesswap required

Why this step matters: Correct local comparisons are the core decision point that drives every swap in bubble sort.

Step 3

Swap operation

In-place exchange of adjacent values.

Swap the out-of-order adjacent pairBefore swap14258exchange neighborsAfter swap12458

Why this step matters: Swapping only out-of-order neighbors preserves stability while moving larger values rightward.

Step 4

Early-exit flag

Stop when a full pass makes zero swaps.

Full pass with zero swaps means the array is already sortedPass input12458swaps this pass = 0stop early: array is sorted

Why this step matters: Early exit avoids unnecessary passes and gives near-sorted inputs a much faster best-case runtime.

How It Compares

vs Merge Sort

When to choose this: Choose bubble sort only for learning or tiny datasets.

Tradeoff: Merge sort is much faster for non-trivial input sizes.

vs Quick Sort

When to choose this: Bubble is simpler to explain line-by-line.

Tradeoff: Quick sort is far better in practical runtime.

vs Insertion Sort

When to choose this: Bubble may be easier to visualize in classrooms.

Tradeoff: Insertion sort usually performs fewer writes on near-sorted data.

Real-World Stories and Company Examples

CS education platforms

Learning environments use bubble sort visualizations to teach comparisons and swaps before advanced algorithms.

Takeaway: Bubble sort is a strong pedagogy tool, not a production workhorse.

Embedded prototypes

Tiny fixed-size arrays in constrained firmware sometimes use simple O(n^2) routines for readability.

Takeaway: For very small n, code simplicity can outweigh asymptotic optimality.

Interview prep companies

Candidate training often starts with bubble sort to build intuition for loop invariants and boundary handling.

Takeaway: Foundational understanding improves mastery of faster sorts later.

Implementation Guide

Stop once a pass makes no swaps, indicating the list is already sorted.

Complexity: Average/Worst O(n^2), Best O(n), Space O(1)

Bubble sort with early-exit optimization

function bubbleSort(values: number[]): number[] {
  const sortedValues = [...values]
  for (let passIndex = 0; passIndex < sortedValues.length - 1; passIndex += 1) {
    let didSwap = false
    for (let compareIndex = 0; compareIndex < sortedValues.length - 1 - passIndex; compareIndex += 1) {
      if (sortedValues[compareIndex] > sortedValues[compareIndex + 1]) {
        ;[sortedValues[compareIndex], sortedValues[compareIndex + 1]] = [sortedValues[compareIndex + 1], sortedValues[compareIndex]]
        didSwap = true
      }
    }
    if (!didSwap) break
  }
  return sortedValues
}

Common Problems and Failure Modes

  • Running full n passes even when array is already sorted.
  • Ignoring shrinking upper bound and doing redundant comparisons.
  • Using bubble sort on large production datasets.
  • Off-by-one errors in inner loop boundary.
  • Assuming O(n) behavior without early-exit optimization.

Tips and Tricks

  • Bubble sort is mainly for learning and tiny inputs, not production-scale datasets.
  • Use early-exit flag so already-sorted data finishes in linear time.
  • Shrink the inner loop boundary each pass because the tail becomes sorted.
  • Step through a five-element example manually to internalize swap flow.

When to Use

Use these signals to decide if this data structure/algorithm is the right fit before implementation.

Real-system usage signals

  • Great for learning sorting fundamentals and swap-based ordering.
  • Very easy to implement and debug step-by-step.
  • Can short-circuit early when input is already sorted.

LeetCode-specific tips (including pattern-identification signals)

  • Identification signal: educational adjacent-swap process is required explicitly or for teaching mechanics.
  • Identification signal: problem expects simple in-place sort with tiny inputs where clarity matters more than scale.
  • If prompt emphasizes repeated neighbor comparisons/swaps, bubble sort pattern is being tested.
  • For Bubble Sort questions, start by naming the core invariant before writing code.
  • Use the constraint section to set time/space target first, then pick the data structure/algorithm.
  • Solve one tiny example by hand and map each transition to your variables before implementing.
  • Run adversarial cases: empty input, duplicates, max-size input, and sorted/reverse patterns when relevant.
  • During interviews, explain why your approach is the right pattern for this prompt, not just why the code works.

LeetCode Progression (Easy to Hard)

Back to DSA Guide Catalog
#ProblemDifficultyTypical Complexity
1Valid AnagramEasyO(n log n) with sorting
2Merge Sorted ArrayEasyO(n+m)
3Height CheckerEasyO(n log n)
4Sort an ArrayMediumO(n^2) for bubble approach
5Sort ColorsMediumO(n) optimal, O(n^2) naive bubble
6Largest NumberMediumO(n log n)
7Wiggle Sort IIMediumO(n log n)
8Sort ListMediumO(n log n)
9Count of Smaller Numbers After SelfHardO(n log n)
10Reverse PairsHardO(n log n)