Speed:
Unsorted
Comparing
Current Element
Sorted
Length:
Bubble Sort
A simple comparison-based algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.

Statistics

Iterations
0
Swaps
0

Complexity Analysis

Case
Best
Average
Worst
Time
O(n)
O(n²)
O(n²)
Space
O(1)

How It Works

  1. Start at the beginning of the array
  2. Compare adjacent elements. If the first is greater than the second, swap them
  3. Move to the next pair of elements and repeat the comparison and swap if necessary
  4. After one complete pass, the largest element will be at the end. Repeat the process for the remaining elements

Best (O(n))

When the array is already sorted, bubble sort makes only one pass through the array with no swaps.

Average (O(n²))

For random arrays, bubble sort still requires quadratic time.

Worst (O(n²))

When the array is sorted in reverse order, bubble sort must make the maximum number of comparisons and swaps.

function bubbleSort(arr) {
  const n = arr.length;

  for (let i = 0; i < n - 1; i++) {
    let swapped = false;

    for (let j = 0; j < n - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        // Swap elements
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
        swapped = true;
      }
    }

    // If no swapping occurred in this pass,
    // array is sorted
    if (!swapped) break;
  }

  return arr;
}