GrokkingSoftwareEngineering Help

Bubble Sort

Reading time: 10 minutes

Bubble sort is one of the simplest sorting algorithms. It works by repeatedly stepping through the array, comparing adjacent elements, and swapping them if they are in the wrong order. The algorithm gets its name because smaller elements "bubble" to the top (beginning) of the array while larger elements sink to the bottom (end).

Interactive Visualization

Watch bubble sort in action. Click Start to begin, adjust the speed, or change the array size.

How It Works

Bubble sort makes multiple passes through the array:

  1. Compare adjacent elements (positions i and i+1)

  2. Swap them if the left element is greater than the right element

  3. Repeat until reaching the end of the unsorted portion

  4. After each pass, the largest unsorted element is in its final position

  5. Continue passes until no swaps are needed

Implementation

function bubbleSort(arr) { const n = arr.length; for (let i = 0; i < n - 1; i++) { let swapped = false; // Each pass bubbles the largest unsorted element to the end for (let j = 0; j < n - 1 - i; j++) { if (arr[j] > arr[j + 1]) { // Swap adjacent elements [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; swapped = true; } } // Optimization: if no swaps occurred, array is already sorted if (!swapped) break; } return arr; }

Complexity Analysis

Case

Time Complexity

When It Occurs

Best

O(n)

Array is already sorted (with early termination optimization)

Average

O(n²)

Random order

Worst

O(n²)

Array is sorted in reverse order

Space complexity: O(1) — bubble sort is an in-place algorithm.

When to Use Bubble Sort

Bubble sort is rarely used in practice due to its O(n²) complexity. However, it has some niche uses:

  • Educational purposes — its simplicity makes it ideal for teaching sorting concepts

  • Nearly sorted data — with the early termination optimization, it performs well when the array is almost sorted

  • Small datasets — for very small arrays (< 10 elements), the overhead of more complex algorithms may not be worth it

For production code, prefer algorithms like quick sort, merge sort, or the built-in sorting functions in your language.

Summary

  • Bubble sort compares and swaps adjacent elements repeatedly

  • It has O(n²) time complexity in the average and worst cases

  • The early termination optimization improves best-case performance to O(n)

  • It is an in-place, stable sorting algorithm

  • Use it for learning; prefer faster algorithms for real applications

Last modified: 01 February 2026