Speed:

Bubble Sort

Time: O(n²)Space: O(1)Stable

💡How It Works

This sorting algorithm compares the adjacent elements and sorts them if they are in the wrong order. It repeats this process times for the array to be sorted.

It's called "bubble" sort because smaller elements slowly "bubble up" to the top (beginning) of the array with each pass, like bubbles rising in water.

💻Implementation

function bubbleSort(arr) {
  let n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    let swapped = false;
    for (let j = 0; j < n - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        // swap
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
        swapped = true;
      }
    }
    if (!swapped) break;
  }
  return arr;
}

🔍Deeper Look

If you take a broader look, it is like taking the biggest element and placing it at the end of the array, then repeating this process until the array is sorted. Bubble Sort is a stable sort, meaning that elements with equal values maintain their relative order after sorting — important for multi-level sorting (like sorting by grade, then by name).

🧪 Stress Test

Bubble Sort is sometimes used in embedded or very low-level testing as a "canary" algorithm to validate a basic sorting function.

🧙‍♂️ Variants in Practice

Bubble Sort is too slow for large datasets. But variants like Cocktail Shaker Sort(a bidirectional version) are more efficient in some situations.