Searching & Sorting AlgorithmsBeginner LevelStudy Time: 10 mins

Bubble Sort Algorithm

Bubble Sort repeatedly steps through an array, comparing adjacent elements and swapping them if they are in wrong order until the dataset is sorted.

Loading visualizer workspace...

Bubble Sort Worked Execution Trace

Sample Input:Input Array: [5, 1, 4, 2, 8]
Step 1

Pass 1 - First Compare & Swap (5, 1)

Compare adjacent elements 5 and 1. Since 5 > 1, swap them.

[5, 1, 4, 2, 8] -> 5 > 1 -> Swap -> [1, 5, 4, 2, 8]
Larger value 5 advances right.
Step 2

Pass 1 - Continuous Bubbling (5, 4 & 5, 2)

Compare (5, 4) -> Swap -> [1, 4, 5, 2, 8]. Compare (5, 2) -> Swap -> [1, 4, 2, 5, 8].

[1, 4, 2, 5, 8] -> Compare (5, 8) -> No swap needed.
Pass 1 completes. Maximum value 8 is now locked at final right index.
Step 3

Pass 2 - Second Max Placement (4, 2)

Compare (1, 4) -> OK. Compare (4, 2) -> Swap -> [1, 2, 4, 5, 8].

Final Sorted Output: [1, 2, 4, 5, 8]
Pass 2 locks value 5. Array is completely sorted.

Real-world analogy: Air Bubbles in Water

Adjacent Swap
Hover over items for details

Larger air bubbles rise faster to the top of water. In bubble sort, the largest unsorted numbers bubble up to the right side with each pass.

  • Adjacent Swap= If arr[j] > arr[j+1], swap them.

Complexity analysis

Scenario Simulator: Dataset Size (N = 500)
Presets:
N = 10N = 10,000
Complexity Curve MapBubble Sort: O(N²) Quadratic Time
Time (t)Size N (500)N = 500O(N²)O(N log N)O(N)O(log N)O(1)Bubble Sort Nest
Time Steps (N=500)

250,000 steps (Quadratic)

O(N²) Quadratic Time

Space Footprint

O(1) In-Place Space

Memory growth rate as N expands.

Performance Rank
Heavy Tier

Relative efficiency rating for large N.

OperationTime ComplexitySpace Complexity
Best Case (Optimized)O(N)O(1)
Worst CaseO(N²)O(1)

Code implementations

function bubbleSort(arr) {
  const n = arr.length;
  for (let i = 0; i < n; i++) {
    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]];
      }
    }
  }
  return arr;
}

Real-world applications

Case 01

Educational Tool

Teaches fundamental sorting and pointer concepts.

Case 02

Nearly Sorted Arrays

Runs in O(N) when only 1 or 2 elements are misplaced.

Interview questions

Topic Knowledge Test & Assessment

10 Questions Assessment

Bubble Sort Algorithm Mastery Test

Evaluate your knowledge of adjacent comparison swaps, max element bubbling, and early exit optimizations.