Skip to content

Bubble Sort Algorithm

Medium ~30 min

What you'll build

A `bubbleSort(arr)` function that sorts an array of numbers in ascending order and returns an array of snapshots showing the array after each pass.

Goals

  • Implement a classic sorting algorithm
  • Use nested loops to compare and swap elements
  • Track the algorithm's progress through snapshots
  • Understand why bubble sort is O(n²)

Prerequisites

  • Arrays and array indexing
  • Nested for loops
  • Variable swapping with a temp variable

Steps

  1. 1

    Set up the outer loop

    Bubble sort makes multiple passes through the array. Each pass moves the largest unsorted element to its correct position. The outer loop controls the number of passes.

    Code
    function bubbleSort(arr) {
      const a = [...arr]; // copy to avoid mutation
      const snapshots = [[...a]];
      for (let i = 0; i < a.length - 1; i++) {
        // inner loop comes next
      }
      return { sorted: a, snapshots };
    }

    Expected result

    The function skeleton is ready with a copy of the input array.

  2. 2

    Add the inner comparison loop

    Inside the outer loop, compare adjacent elements and swap them if they are in the wrong order. After each pass, take a snapshot of the array state.

    Code
        for (let j = 0; j < a.length - 1 - i; j++) {
          if (a[j] > a[j + 1]) {
            const temp = a[j];
            a[j] = a[j + 1];
            a[j + 1] = temp;
          }
        }
        snapshots.push([...a]);

    Expected result

    Each pass swaps adjacent out-of-order elements, bubbling larger values to the right.

  3. 3

    Test with an unsorted array

    Call the function with an unsorted array and inspect both the sorted result and the snapshots to see how the array evolves.

    Code
    const result = bubbleSort([5, 3, 8, 1, 2]);
    console.log('Sorted:', result.sorted);
    console.log('Passes:', result.snapshots.length);
    result.snapshots.forEach((snap, i) => console.log(`Pass ${i}:`, snap));

    Expected result

    Sorted: [1, 2, 3, 5, 8] with snapshots showing each intermediate state.

  4. 4

    Add an optimization

    Add a flag to detect if any swaps were made in a pass. If no swaps occurred, the array is already sorted and we can exit early.

    Code
      for (let i = 0; i < a.length - 1; 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;
          }
        }
        snapshots.push([...a]);
        if (!swapped) break; // early exit
      }

    Expected result

    Nearly-sorted arrays finish in fewer passes thanks to the early exit.

  5. 5

    Add input validation

    At the entry of the main logic, add input validation: check that the input is a valid number and within the allowed range, and show a clear message for invalid input instead of crashing. This is the first line of defense for a robust program.

    Code
    function validateInput(value, min, max) {
      if (typeof value !== "number" || Number.isNaN(value)) {
        throw new Error(`Invalid input: ${value} is not a number`);
      }
      if (value < min || value > max) {
        throw new Error(`Input ${value} out of range [${min}, ${max}]`);
      }
      return value;
    }
    
    // Usage
    const input = validateInput(rawInput, 1, 100);

    Expected result

    Invalid input (non-number or out of range) throws a clear error message; valid input passes through normally.

Try it yourself

What you learned

You implemented a classic sorting algorithm with nested loops, learned to track algorithm state through snapshots, and added an optimization (early exit) — skills that transfer to understanding any comparison-based algorithm.

Related Resources

Related Lessons

  • Loops

    Nested loops drive the comparison passes.

  • Arrays

    Array indexing and swapping are core to the algorithm.

Related Practice

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic