DEV Community

Ankit Maheshwari
Ankit Maheshwari

Posted on • Originally published at bitveen.com

Bubble Sort Explained Simply — Algorithm, Code & Complexity

Bubble Sort isn't used in production — but it's the best algorithm to learn sorting logic because every step is visible and intuitive.

🔹 The Idea

Repeatedly compare adjacent elements. If wrong order, swap. Larger elements "bubble up" to the end.

📋 Step-by-Step: [5, 3, 8, 2]

Pass 1: 5↔3 → 5 vs 8 → 8↔2 → [3, 5, 2, **8**]
Pass 2: 3 vs 5 → 5↔2 → [3, 2, **5**, 8]
Pass 3: 3↔2 → [**2**, **3**, 5, 8]

💻 Optimised JavaScript

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]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
        swapped = true;
      }
    }
    if (!swapped) break; // Early exit — O(n) best case
  }
  return arr;
}
Enter fullscreen mode Exit fullscreen mode

⏱ Complexity

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

Part 7 of the Bitveen DSA Series. Originally published at bitveen.com

Top comments (0)